import { MemberState } from "@app/shared/types/member";
import { requireLogin, requireMemberState, requireRole } from "../middleware/auth";
import { batchInsertMemberRank, getAllRanks, getPromotionHistorySummary, getPromotionsOnDay, insertMemberRank } from "../services/db/rankService";
import { BatchPromotion, BatchPromotionMember } from '@app/shared/schemas/promotionSchema'

import express = require('express');
import { logger } from "../services/logging/logger";
const r = express.Router();
const ur = express.Router();


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

//insert a new latest rank for a user
ur.post('/', [requireRole(["17th Command", "17th Administrator", "17th HQ"]), requireMemberState(MemberState.Member)], async (req: express.Request, res: express.Response) => {
    try {
        const change = req.body.promotions as BatchPromotionMember[];
        const approver = req.body.approver as number;
        const author = req.user.id;
        if (!change) res.sendStatus(400);

        await batchInsertMemberRank(change, author, approver);
        logger.info('app', 'Promotion batch submitted', { author: author })
        res.sendStatus(201);
    } catch (error) {
        logger.error(
            'app',
            'Failed to post rank change',
            {
                error: error instanceof Error ? error.message : String(error),
                stack: error instanceof Error ? error.stack : undefined,
            }
        );
        res.status(500).json({ error: 'Failed to update ranks' });
    }
});

ur.get('/', async (req: express.Request, res: express.Response) => {
    try {
        const promos = await getPromotionHistorySummary();
        res.status(200).json(promos);
    } catch (error) {
        logger.error(
            'app',
            'Failed to get rank change history',
            {
                error: error instanceof Error ? error.message : String(error),
                stack: error instanceof Error ? error.stack : undefined,
            }
        );
        res.sendStatus(500);
    }
});

ur.get('/:day', async (req: express.Request, res: express.Response) => {
    try {
        if (!req.params.day) res.sendStatus(400);

        var day = new Date(req.params.day)
        const promos = await getPromotionsOnDay(day);
        res.status(200).json(promos);
    } catch (error) {
        logger.error(
            'app',
            'Failed to get rank change history on day',
            {
                day: day,
                error: error instanceof Error ? error.message : String(error),
                stack: error instanceof Error ? error.stack : undefined,
            }
        );
        res.sendStatus(500);
    }
})

//get all ranks
r.get('/', async (req, res) => {
    try {
        const ranks = await getAllRanks();
        res.json(ranks);
    } catch (error) {
        logger.error(
            'app',
            'Failed to get all ranks',
            {
                error: error instanceof Error ? error.message : String(error),
                stack: error instanceof Error ? error.stack : undefined,
            }
        );
        res.status(500).json({ error: 'Internal server error' });
    }
});

export const ranks = r;
export const memberRanks = ur;