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

/* GET requests */
router.get('/requests', async function (req, res, next) {
    const student_id = req.query.student_id;
    const team_id = req.query.team_id;
    const supplier_id = req.query.supplier_id;
    const part_id = req.query.part_id;
    const order_id = req.query.order_id;
    const status = req.query.status;

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

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

    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)
                );
        }
    }

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

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

    if (status) {
        let validation_tuple =
            await paramValidation.validate_request_status(status);
        if (!validation_tuple.is_valid) {
            return res
                .status(400)
                .json(
                    errorHandling.return_error_400(validation_tuple.error_msg)
                );
        }
    }

    // Assemble SQL query based on provided query params
    const query = db.prepare_select_statement('requests', req.query);
    // Retrieve rows from database
    try {
        const result = await db.query(query, Object.values(req.query));

        // Transform subtotal to number
        result.rows.forEach((row) =>
            paramTransformation.transform_request_monies(row)
        );

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

/* POST requests */
router.post('/requests', async function (req, res, next) {
    // Create dict to store SQL "INSERT INTO"/"VALUES" params
    let params = {};
    // Retrieve request body properties
    const student_id = req.body.student_id || null;
    const team_id = req.body.team_id || null;
    const supplier_id = req.body.supplier_id || null;
    const part_id = req.body.part_id || null;
    const order_id = req.body.order_id || null; // Optional
    const status = req.body.status || null;
    const quantity = req.body.quantity || null;
    const subtotal = req.body.subtotal || null;

    let validation_tuple;
    // Validate foreign key properties
    validation_tuple = await paramValidation.validate_student_id(
        student_id,
        paramValidation.ParamType.BODY
    );
    if (!validation_tuple.is_valid) {
        return res
            .status(404)
            .json(errorHandling.return_error_404(validation_tuple.error_msg));
    }
    params.student_id = student_id;
    validation_tuple = await paramValidation.validate_supplier_id(
        supplier_id,
        paramValidation.ParamType.BODY
    );
    if (!validation_tuple.is_valid) {
        return res
            .status(404)
            .json(errorHandling.return_error_404(validation_tuple.error_msg));
    }
    params.supplier_id = supplier_id;
    validation_tuple = await paramValidation.validate_team_id(
        team_id,
        paramValidation.ParamType.BODY
    );
    if (!validation_tuple.is_valid) {
        return res
            .status(404)
            .json(errorHandling.return_error_404(validation_tuple.error_msg));
    }
    params.team_id = team_id;
    validation_tuple = await paramValidation.validate_part_id(
        part_id,
        paramValidation.ParamType.BODY
    );
    if (!validation_tuple.is_valid) {
        return res
            .status(404)
            .json(errorHandling.return_error_404(validation_tuple.error_msg));
    }
    params.part_id = part_id;
    validation_tuple = paramValidation.validate_request_status(status);
    if (!validation_tuple.is_valid) {
        return res
            .status(400)
            .json(errorHandling.return_error_400(validation_tuple.error_msg));
    }
    params.status = status;
    validation_tuple = paramValidation.build_validation_tuple(
        quantity,
        paramValidation.checkInteger(quantity),
        'Failed to convert value ' + quantity + ' for quantity to an integer.'
    );
    if (!validation_tuple.is_valid) {
        return res
            .status(400)
            .json(errorHandling.return_error_400(validation_tuple.error_msg));
    }
    params.quantity = quantity;
    validation_tuple = paramValidation.build_validation_tuple(
        subtotal,
        paramValidation.checkNumber(subtotal),
        'Failed to convert value ' + subtotal + ' for subtotal to a number.'
    );
    if (!validation_tuple.is_valid) {
        return res
            .status(400)
            .json(errorHandling.return_error_400(validation_tuple.error_msg));
    }
    params.subtotal = subtotal.toFixed(2);

    if (order_id) {
        validation_tuple = await paramValidation.validate_order_id(
            order_id,
            paramValidation.ParamType.BODY
        );
        if (!validation_tuple.is_valid) {
            return res
                .status(404)
                .json(
                    errorHandling.return_error_404(validation_tuple.error_msg)
                );
        }

        params.order_id = order_id;
    }

    // Generate request timestamp
    params.request_timestamp = new Date().toISOString();

    // Assemble SQL query based on provided query params
    const query = db.prepare_insert_statement('requests', 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.'
            );
        }

        // Transform subtotal to number
        result.rows[0] = paramTransformation.transform_request_monies(
            result.rows[0]
        );

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

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

    if (request_id) {
        let validation_tuple = await paramValidation.validate_request_id(
            request_id,
            paramValidation.ParamType.PATH
        );
        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 requests WHERE request_id = $1',
            [request_id]
        );

        // Transform subtotal to number
        result.rows[0] = paramTransformation.transform_request_monies(
            result.rows[0]
        );

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

/* PATCH request by ID */
router.patch('/requests/:request_id', async function (req, res, next) {
    // Create a dict to store SQL "WHERE" params
    let where = {};
    // Validate path param
    const request_id = req.params.request_id;
    if (request_id) {
        let validation_tuple = await paramValidation.validate_request_id(
            request_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.request_id = request_id;
    }

    // Retrieve request body parameters
    const order_id = req.body.order_id || null; // Optional
    const status = req.body.status || null; // Optional
    const quantity = req.body.quantity || null; // Optional
    const subtotal = req.body.subtotal || null; // Optional

    // Create a dict to store "SET" params
    let set = {};
    let proceed = false;
    let validation_tuple;
    // Validate properties
    if (order_id === 'unset') {
        set.order_id = null;
        proceed = true;
    } else if (order_id) {
        validation_tuple = await paramValidation.validate_order_id(
            order_id,
            paramValidation.ParamType.BODY
        );
        if (!validation_tuple.is_valid) {
            return res
                .status(400)
                .json(
                    errorHandling.return_error_400(validation_tuple.error_msg)
                );
        }

        // Update set dict
        set.order_id = order_id;
        proceed = true;
    }
    if (status) {
        validation_tuple = paramValidation.validate_request_status(status);
        if (!validation_tuple.is_valid) {
            return res
                .status(400)
                .json(
                    errorHandling.return_error_400(validation_tuple.error_msg)
                );
        }

        // Update set dict
        set.status = status;
        proceed = true;
    }
    if (quantity) {
        validation_tuple = paramValidation.build_validation_tuple(
            quantity,
            paramValidation.checkInteger(quantity),
            'Failed to convert value ' +
                quantity +
                ' for quantity to an integer.'
        );
        if (!validation_tuple.is_valid) {
            return res
                .status(400)
                .json(
                    errorHandling.return_error_400(validation_tuple.error_msg)
                );
        }

        // Update set dict
        set.quantity = quantity;
        proceed = true;
    }
    if (subtotal) {
        validation_tuple = paramValidation.build_validation_tuple(
            subtotal,
            paramValidation.checkNumber(subtotal),
            'Failed to convert value ' + subtotal + ' for subtotal to a number.'
        );
        if (!validation_tuple.is_valid) {
            return res
                .status(400)
                .json(
                    errorHandling.return_error_400(validation_tuple.error_msg)
                );
        }

        // Update set dict
        set.subtotal = subtotal.toFixed(2);
        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('requests', 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.'
            );
        }

        // Transform subtotal to number
        result.rows[0] = paramTransformation.transform_request_monies(
            result.rows[0]
        );

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

/* DELETE request by ID */
router.delete('/requests/:request_id', async function (req, res, next) {
    // Validate path param
    const request_id = req.params.request_id;
    if (request_id) {
        let validation_tuple = await paramValidation.validate_request_id(
            request_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 requests WHERE request_id = $1',
            [request_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;
