// Express routing
const express = require('express');
const router = express.Router();
// Database connection
const db = require('../db');
// Param validation functions
const paramValidation = require('../param_validation');
// Error handling functions
const errorHandling = require('../error_handling');
const { DatabaseError } = require('pg');

/* GET suppliers */
router.get('/suppliers', async function (req, res, next) {
    let url = req.query.url;

    if (url) {
        url = url.includes('://') ? url : 'http://' + url;
        let validation_tuple = paramValidation.build_validation_tuple(
            url,
            paramValidation.checkURL(url),
            'Failed to convert value ' + url + ' for url to a valid URL string.'
        );
        if (!validation_tuple.is_valid) {
            return res
                .status(400)
                .json(
                    errorHandling.return_error_400(validation_tuple.error_msg)
                );
        }
        url = url.includes('https://')
            ? url.replace('https://', 'http://')
            : url;

        req.query.url = url;
    }

    // Assemble SQL query based on provided query params
    const query = db.prepare_select_statement('suppliers', req.query);
    // Retrieve rows from database
    try {
        const result = await db.query(query, Object.values(req.query));
        return res.status(200).json(result.rows);
    } catch (error) {
        return res
            .status(500)
            .json(errorHandling.return_error_500(error.message));
    }
});

/* POST suppliers */
router.post('/suppliers', async function (req, res, next) {
    // Create dict to store SQL "INSERT INTO"/"VALUES" params
    let params = {};
    // Retrieve request body properties
    let url = req.body.url || null;
    const name = req.body.name || null;

    let validation_tuple;
    // Validate property types
    url = url.includes('://') ? url : 'http://' + url;
    validation_tuple = paramValidation.build_validation_tuple(
        url,
        paramValidation.checkURL(url),
        'Failed to convert value ' + url + ' for url to a valid URL string.'
    );
    if (!validation_tuple.is_valid) {
        return res
            .status(400)
            .json(errorHandling.return_error_400(validation_tuple.error_msg));
    }
    url = url.includes('https://') ? url.replace('https://', 'http://') : url;
    params.url = url;

    validation_tuple = paramValidation.validate_supplier_name(url, name);
    if (!validation_tuple.is_valid) {
        return res
            .status(400)
            .json(errorHandling.return_error_400(validation_tuple.error_msg));
    }
    params.name = name;

    // Assemble SQL query based on provided query params
    const query = db.prepare_insert_statement('suppliers', params);
    // Attempt to write row to database
    try {
        const result = await db.query(query, Object.values(params));
        // Make sure row was created
        if (!result.rowCount) {
            throw new DatabaseError(
                'Database insertion failed: no rows affected.'
            );
        }

        return res.status(201).json(result.rows[0]);
    } catch (error) {
        return res
            .status(500)
            .json(errorHandling.return_error_500(error.message));
    }
});

/* GET suppliers by ID */
router.get('/suppliers/:supplier_id', async function (req, res, next) {
    const supplier_id = req.params.supplier_id;

    if (supplier_id) {
        let validation_tuple = await paramValidation.validate_supplier_id(
            supplier_id,
            paramValidation.ParamType.QUERY
        );
        if (!validation_tuple.is_valid) {
            return res
                .status(404)
                .json(
                    errorHandling.return_error_404(validation_tuple.error_msg)
                );
        }
    }

    // Retrieve row from database
    try {
        const result = await db.query(
            'SELECT * FROM suppliers WHERE supplier_id = $1',
            [supplier_id]
        );
        return res.status(200).json(result.rows[0]);
    } catch (error) {
        return res
            .status(500)
            .json(errorHandling.return_error_500(error.message));
    }
});

/* PATCH suppliers by ID */
router.patch('/suppliers/:supplier_id', async function (req, res, next) {
    // Create a dict to store SQL "WHERE" params
    let where = {};
    // Validate path param
    const supplier_id = req.params.supplier_id;
    if (supplier_id) {
        let validation_tuple = await paramValidation.validate_supplier_id(
            supplier_id,
            paramValidation.ParamType.PATH
        );
        if (!validation_tuple.is_valid) {
            return res
                .status(404)
                .json(
                    errorHandling.return_error_404(validation_tuple.error_msg)
                );
        }

        // Update where dict
        where.supplier_id = supplier_id;
    }

    let url = req.body.url || null;
    const name = req.body.name || null;

    // Create a dict to store "SET" params
    let set = {};
    let proceed = false;
    let validation_tuple;

    // Validate types of properties
    if (url) {
        url = url.includes('://') ? url : 'http://' + url;
        validation_tuple = paramValidation.build_validation_tuple(
            url,
            paramValidation.checkURL(url),
            'Failed to convert value ' + url + ' for url to a valid URL string.'
        );
        if (!validation_tuple.is_valid) {
            return res
                .status(400)
                .json(
                    errorHandling.return_error_400(validation_tuple.error_msg)
                );
        }
        url = url.includes('https://')
            ? url.replace('https://', 'http://')
            : url;

        set.url = url;
        proceed = true;
    }
    if (name) {
        validation_tuple = paramValidation.validate_supplier_name(url, name);
        if (!validation_tuple.is_valid) {
            return res
                .status(400)
                .json(
                    errorHandling.return_error_400(validation_tuple.error_msg)
                );
        }

        set.name = name;
        proceed = true;
    }

    // Make sure at least one property was provided for update
    if (!proceed) {
        return res
            .status(400)
            .json(
                errorHandling.return_error_400(
                    'At least one property must be provided.'
                )
            );
    }

    // Assemble SQL query based on provided query params
    const query = db.prepare_update_statement('suppliers', set, where);
    // Attempt to write row to database
    try {
        const result = await db.query(
            query,
            Object.values(set).concat(Object.values(where))
        );
        // Make sure row was created
        if (!result.rowCount) {
            throw new DatabaseError(
                'Database update failed: no rows affected.'
            );
        }

        return res.status(200).json(result.rows[0]);
    } catch (error) {
        return res
            .status(500)
            .json(errorHandling.return_error_500(error.message));
    }
});

/* DELETE suppliers by ID */
router.delete('/suppliers/:supplier_id', async function (req, res, next) {
    // Validate path param
    const supplier_id = req.params.supplier_id;
    if (supplier_id) {
        let validation_tuple = await paramValidation.validate_supplier_id(
            supplier_id,
            paramValidation.ParamType.PATH
        );
        if (!validation_tuple.is_valid) {
            return res
                .status(404)
                .json(
                    errorHandling.return_error_404(validation_tuple.error_msg)
                );
        }
    }

    // Delete row from database
    try {
        const result = await db.query(
            'DELETE FROM suppliers WHERE supplier_id = $1',
            [supplier_id]
        );

        if (result.rowCount === 1) {
            return res.status(204).send();
        } else {
            throw new DatabaseError(
                'Database delete failed: no rows affected.'
            );
        }
    } catch (error) {
        return res
            .status(500)
            .json(errorHandling.return_error_500(error.message));
    }
});

module.exports = router;
