const express = require('express');
const r = express.Router();
const ur = express.Router();

import { MemberState } from '@app/shared/types/member';
import pool from '../db';
import { requireLogin, requireMemberState, requireRole } from '../middleware/auth';
import { assignUserGroup, createGroup } from '../services/rolesService';

r.use(requireLogin)
ur.use(requireLogin)

//manually assign a member to a group
ur.post('/', [requireMemberState(MemberState.Member), requireRole("17th Administrator")], async (req, res) => {
    try {
        const body = req.body;

        assignUserGroup(body.member_id, body.role_id);

        res.sendStatus(201);
    } catch (err) {
        console.error('Insert failed:', err);
        res.status(500).json({ error: 'Failed to add to group' });
    }
});

//manually remove member from group
ur.delete('/', [requireMemberState(MemberState.Member), requireRole("17th Administrator")], async (req, res) => {
    try {
        const body = req.body;
        console.log(body);

        const sql = 'DELETE FROM members_roles WHERE member_id = ? AND role_id = ?'
        await pool.query(sql, [body.member_id, body.role_id])

        res.sendStatus(200);
    }
    catch (err) {
        console.error("delete failed: ", err)
        res.status(500).json({ error: 'Failed to remove from group' });

    }
})

//get all roles
r.get('/', [requireMemberState(MemberState.Member)], async (req, res) => {
    try {
        var con = await pool.getConnection();

        // Get all roles
        const roles = await con.query('SELECT * FROM roles;');

        // Get all members for each role
        const membersRoles = await con.query(`
            SELECT mr.role_id, v.*
            FROM members_roles mr
            JOIN view_member_rank_unit_status_latest v ON mr.member_id = v.member_id
            `);


        // Group members by role_id
        const roleIdToMembers = {};
        for (const row of membersRoles) {
            if (!roleIdToMembers[row.role_id]) roleIdToMembers[row.role_id] = [];
            // Remove role_id from member object
            const { role_id, ...member } = row;
            roleIdToMembers[role_id].push(member);
        }

        // Attach members to each role
        const result = roles.map(role => ({
            ...role,
            members: roleIdToMembers[role.id] || []
        }));

        res.json(result);
    } catch (err) {
        console.error(err);
        res.status(500).json({ error: 'Internal server error' });
    } finally {
        con.release();
    }
});

//create a new role
r.post('/', [requireMemberState(MemberState.Member), requireRole("17th Administrator")], async (req, res) => {
    try {
        const { name, color, description } = req.body;
        console.log('Creating role:', { name, color, description });
        if (!name || !color) {
            return res.status(400).json({ error: 'Name and color are required' });
        }

        const hexColorRegex = /^#([0-9A-Fa-f]{6})$/;
        if (!hexColorRegex.test(color)) {
            return res.status(400).json({ error: 'Color must be a valid hex color (#ffffff)' });
        }

        await createGroup(name, color, description);

        res.sendStatus(201);
    } catch (err) {
        console.error('Insert failed:', err);
        res.status(500).json({ error: 'Failed to create role' });
    }
})

r.delete('/:id', [requireMemberState(MemberState.Member), requireRole("17th Administrator")], async (req, res) => {
    try {
        const id = req.params.id;

        const sql = 'DELETE FROM roles WHERE id = ?';
        const res = await pool.query(sql, [id]);
        res.sendStatus(200);
    } catch (error) {
        console.log(error);
        res.sendStatus(500);
    }
})

export const roles = r;
export const memberRoles = ur;
