const express = require('express');
const router = express.Router();

import { Request, Response } from 'express';
import pool from '../db';
import { requireLogin, requireMemberState, requireRole } from '../middleware/auth';
import { getUserActiveLOA } from '../services/loaService';
import { getMemberSettings, getMembersFull, getMembersLite, getUserData, setUserSettings } from '../services/memberService';
import { getUserRoles } from '../services/rolesService';
import { memberSettings, MemberState } from '@app/shared/types/member';

//get all users
router.get('/', [requireLogin, requireMemberState(MemberState.Member)], async (req, res) => {
    try {
        const result = await pool.query(
            `SELECT
            v.*,
            CASE
                WHEN EXISTS (
                SELECT 1
                FROM leave_of_absences l
                WHERE l.member_id = v.member_id
                    AND l.deleted = 0
                    AND UTC_TIMESTAMP() BETWEEN l.start_date AND l.end_date
                ) THEN 1 ELSE 0
            END AS on_loa
            FROM view_member_rank_unit_status_latest v;`);
        return res.status(200).json(result);
    } catch (err) {
        console.error('Error fetching users:', err);
        return res.status(500).json({ error: 'Failed to fetch users' });
    }
});

router.get('/me', [requireLogin], async (req, res) => {
    if (req.user === undefined)
        return res.sendStatus(401)

    try {
        const { id, name, state } = await getUserData(req.user.id);
        const LOAData = await getUserActiveLOA(req.user.id);

        const roleData = await getUserRoles(req.user.id);

        const userDataFull = { id, name, state, LOAData, roleData };
        res.status(200).json(userDataFull);
    } catch (error) {
        console.error('Error fetching user data:', error);
        return res.status(500).json({ error: 'Failed to fetch user data' });
    }
})

router.get('/settings', [requireLogin], async (req: Request, res: Response) => {
    try {
        let user = req.user.id;
        console.log(user);
        let output = await getMemberSettings(user);
        res.status(200).json(output);
    } catch (error) {
        console.error(error);
        res.status(500).json(error);
    }
})

router.put('/settings', [requireLogin], async (req: Request, res: Response) => {
    try {
        let user = req.user.id;
        let settings: memberSettings = req.body;
        console.log(settings)
        await setUserSettings(user, settings);
        res.sendStatus(200);
    } catch (error) {
        console.error(error);
        res.status(500).json(error);
    }
})

router.post('/lite/bulk', async (req: Request, res: Response) => {
    try {
        let ids = req.body.ids;
        let out = await getMembersLite(ids);
        res.status(200).json(out);
    } catch (error) {
        console.error(error);
        res.status(500).json(error);
    }
})

router.post('/full/bulk', async (req: Request, res: Response) => {
    try {
        let ids = req.body.ids;
        let out = await getMembersFull(ids);
        res.status(200).json(out);
    } catch (error) {
        console.error(error);
        res.status(500).json(error);
    }
})

router.get('/:id', [requireLogin], async (req, res) => {
    try {
        const userId = req.params.id;
        const result = await pool.query('SELECT * FROM view_member_rank_unit_status_latest WHERE id = $1;', [userId]);
        if (result.rows.length === 0) {
            return res.status(404).json({ error: 'User not found' });
        }
        return res.status(200).json(result.rows[0]);
    } catch (err) {
        console.error('Error fetching user:', err);
        return res.status(500).json({ error: 'Failed to fetch user' });
    }
});

//update a user's display name (stub)
router.put('/:id/displayname', async (req, res) => {
    // Stub: not implemented yet
    return res.status(501);
});


export const memberRouter = router;
