// 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 Instructors */
router.get('/instructors', async function (req, res, next) {
    const query = db.prepare_select_statement('instructors', 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));
    }
});

/* GET Instructor by ID */
router.get('/instructors/:instructor_id', async function (req, res, next) {
    const instructor_id = req.params.instructor_id;
    if (instructor_id) {
        let validation_tuple = await paramValidation.validate_instructor_id(
            instructor_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 users.* FROM users JOIN instructors ON users.user_id = instructors.user_id WHERE instructors.instructor_id = $1',
            [instructor_id]
        );
        return res.status(200).json(result.rows[0]);
    } catch (error) {
        return res
            .status(500)
            .json(errorHandling.return_error_500(error.message));
    }
});

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

    // Retrieve request body parameters
    const is_admin = req.body.is_admin || null;

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

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

        set.is_admin = is_admin;
        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('instructors', 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 instructor by ID */
router.delete('/instructors/:instructor_id', async function (req, res, next) {
    // Validate path param
    const instructor_id = req.params.instructor_id;
    if (instructor_id) {
        let validation_tuple = await paramValidation.validate_instructor_id(
            instructor_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 instructors WHERE instructor_id = $1',
            [instructor_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;
