// 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 orders */
router.get('/orders', async function (req, res, next) {
    // Validate query params
    const instructor_id = req.query.instructor_id;
    const supplier_id = req.query.supplier_id;
    if (instructor_id) {
        let validation_tuple = await paramValidation.validate_instructor_id(
            instructor_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)
                );
        }
    }

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

        // Transform total to number
        result.rows.forEach((row) =>
            paramTransformation.transform_order_monies(row)
        );

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

/* POST orders */
router.post('/orders', async function (req, res, next) {
    // Create dict to store SQL "INSERT INTO"/"VALUES" params
    let params = {};
    // Retrieve request body properties
    const instructor_id = req.body.instructor_id || null;
    const supplier_id = req.body.supplier_id || null;
    const is_fulfilled =
        req.body.is_fulfilled === undefined || req.body.is_fulfilled === null
            ? false
            : req.body.is_fulfilled;
    const total = req.body.total || null;

    let validation_tuple;
    // Validate foreign key properties
    validation_tuple = await paramValidation.validate_instructor_id(
        instructor_id,
        paramValidation.ParamType.BODY
    );
    if (!validation_tuple.is_valid) {
        return res
            .status(404)
            .json(errorHandling.return_error_404(validation_tuple.error_msg));
    }
    params.instructor_id = instructor_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;

    // Validate types of other properties
    if (is_fulfilled) {
        validation_tuple = paramValidation.build_validation_tuple(
            is_fulfilled,
            paramValidation.checkBoolean(is_fulfilled),
            'Failed to convert value ' +
                is_fulfilled +
                ' for is_fulfilled to a boolean.'
        );
        if (!validation_tuple.is_valid) {
            return res
                .status(400)
                .json(
                    errorHandling.return_error_400(validation_tuple.error_msg)
                );
        }
    }
    params.is_fulfilled = is_fulfilled;

    // Check that total is a valid number
    validation_tuple = paramValidation.build_validation_tuple(
        total,
        paramValidation.checkNumber(total),
        'Failed to convert value ' + total + ' for total to a number.'
    );
    if (!validation_tuple.is_valid) {
        return res
            .status(400)
            .json(errorHandling.return_error_400(validation_tuple.error_msg));
    }
    params.total = total.toFixed(2);

    // Generate order timestamp
    params.order_timestamp = new Date().toISOString();

    // Assemble SQL query based on provided query params
    const query = db.prepare_insert_statement('orders', 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 total to number
        result.rows[0] = paramTransformation.transform_order_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 order by ID */
router.get('/orders/:order_id', async function (req, res, next) {
    // Validate path param
    const order_id = req.params.order_id;
    if (order_id) {
        let validation_tuple = await paramValidation.validate_order_id(
            order_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 orders WHERE order_id = $1',
            [order_id]
        );

        // Transform total to number
        result.rows[0] = paramTransformation.transform_order_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 order by ID */
router.patch('/orders/:order_id', async function (req, res, next) {
    // Create a dict to store SQL "WHERE" params
    let where = {};
    // Validate path param
    const order_id = req.params.order_id;
    if (order_id) {
        let validation_tuple = await paramValidation.validate_order_id(
            order_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.order_id = order_id;
    }

    const instructor_id = req.body.instructor_id || null;

    // Retrieve request body parameters
    const is_fulfilled =
        req.body.is_fulfilled === undefined || req.body.is_fulfilled === null
            ? null
            : req.body.is_fulfilled; // Optional
    const total = req.body.total || null; // Optional

    // Create a dict to store "SET" params
    let set = {};
    let proceed = false;
    let validation_tuple;
    // Validate types of properties
    if (instructor_id !== null) {
        validation_tuple = paramValidation.build_validation_tuple(
            instructor_id,
            paramValidation.checkInteger(instructor_id),
            'Failed to convert value ' +
                instructor_id +
                ' for instructor_id to a boolean.'
        );
        if (!validation_tuple.is_valid) {
            return res
                .status(400)
                .json(
                    errorHandling.return_error_400(validation_tuple.error_msg)
                );
        }

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

        // Update set dict
        set.is_fulfilled = is_fulfilled;
        proceed = true;
    }
    if (total) {
        validation_tuple = paramValidation.build_validation_tuple(
            total,
            paramValidation.checkNumber(total),
            'Failed to convert value ' + total + ' for total 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.total = total.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('orders', 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 total to number
        result.rows[0] = paramTransformation.transform_order_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 order by ID */
router.delete('/orders/:order_id', async function (req, res, next) {
    // Validate path param
    const order_id = req.params.order_id;
    if (order_id) {
        let validation_tuple = await paramValidation.validate_order_id(
            order_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 orders WHERE order_id = $1',
            [order_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;
