// 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 teams */
router.get('/teams', async function (req, res, next) {
    const section_id = req.query.section_id;
    if (section_id) {
        let validation_tuple = paramValidation.build_validation_tuple(
            section_id,
            paramValidation.checkInteger(section_id),
            'Failed to convert value ' +
                section_id +
                ' for section_id to an integer.'
        );
        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('teams', 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 teams */
router.post('/teams', async function (req, res, next) {
    // Create dict to store SQL "INSERT INTO"/"VALUES" params
    let params = {};
    // Retrieve request body properties
    const name = req.body.name || null; // Optional
    const section_id = req.body.section_id || null;
    const team_num = req.body.team_num || null;
    const locker_num = req.body.locker_num || null;

    let validation_tuple;

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

        params.name = name;
    }

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

    params.section_id = section_id;

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

    params.team_num = team_num;

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

        params.locker_num = locker_num;
    }

    // Assemble SQL query based on provided query params
    const query = db.prepare_insert_statement('teams', 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 team by ID */
router.get('/teams/:team_id', async function (req, res, next) {
    const team_id = req.params.team_id;
    if (team_id) {
        let validation_tuple = await paramValidation.validate_team_id(
            team_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 teams WHERE team_id = $1',
            [team_id]
        );
        return res.status(200).json(result.rows[0]);
    } catch (error) {
        return res
            .status(500)
            .json(errorHandling.return_error_500(error.message));
    }
});

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

    const name = req.body.name || null;
    const section_id = req.body.section_id || null;
    const locker_num = req.body.locker_num || null;

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

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

        set.name = name;
        proceed = true;
    }
    if (section_id) {
        validation_tuple = paramValidation.build_validation_tuple(
            section_id,
            paramValidation.checkInteger(section_id),
            'Failed to convert value ' +
                section_id +
                ' for section_id to a string.'
        );
        if (!validation_tuple.is_valid) {
            return res
                .status(400)
                .json(
                    errorHandling.return_error_400(validation_tuple.error_msg)
                );
        }

        set.section_id = section_id;
        proceed = true;
    }

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

        set.locker_num = locker_num;
        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('teams', 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 team by ID */
router.delete('/teams/:team_id', async function (req, res, next) {
    // Validate path param
    const team_id = req.params.team_id;
    if (team_id) {
        let validation_tuple = await paramValidation.validate_team_id(
            team_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 teams WHERE team_id = $1', [
            team_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;
