// 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 TAs */
router.get('/tas', async function (req, res, next) {
    const query = db.prepare_select_statement('tas', 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 TA by ID */
router.get('/tas/:ta_id', async function (req, res, next) {
    const ta_id = req.params.ta_id;
    if (ta_id) {
        let validation_tuple = await paramValidation.validate_ta_id(
            ta_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 tas ON users.user_id = tas.user_id WHERE tas.ta_id = $1',
            [ta_id]
        );
        return res.status(200).json(result.rows[0]);
    } catch (error) {
        return res
            .status(500)
            .json(errorHandling.return_error_500(error.message));
    }
});

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