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

import { Request, Response } from 'express';
import pool from '../db';
import { closeLOA, createNewLOA, getAllLOA, getLOAbyID, getLoaTypes, getUserLOA, setLOAExtension } from '../services/loaService';
import { LOARequest } from '@app/shared/types/loa';
import { requireLogin, requireRole } from '../middleware/auth';

router.use(requireLogin);

//member posts LOA
router.post("/", async (req: Request, res: Response) => {
    let LOARequest = req.body as LOARequest;
    LOARequest.member_id = req.user.id;
    LOARequest.created_by = req.user.id;
    LOARequest.filed_date = new Date();

    try {
        await createNewLOA(LOARequest);
        res.sendStatus(201);
    } catch (error) {
        console.error(error);
        res.status(500).send(error);
    }
});

//admin posts LOA
router.post("/admin", [requireRole("17th Administrator")], async (req: Request, res: Response) => {
    let LOARequest = req.body as LOARequest;
    LOARequest.created_by = req.user.id;
    LOARequest.filed_date = new Date();
    try {
        await createNewLOA(LOARequest);
        res.sendStatus(201);
    } catch (error) {
        console.error(error);
        res.status(500).send(error);
    }
});

//get my current LOA
router.get("/me", async (req: Request, res: Response) => {
    const user = req.user.id;
    try {
        const result = await getUserLOA(user);
        res.status(200).json(result)
    } catch (error) {
        console.error(error);
        res.status(500).send(error);
    }
})

//get my LOA history
router.get("/history", async (req: Request, res: Response) => {
    try {
        const user = req.user.id;

        const page = Number(req.query.page) || undefined;
        const pageSize = Number(req.query.pageSize) || undefined;

        const result = await getUserLOA(user, page, pageSize);
        res.status(200).json(result)
    } catch (error) {
        console.error(error);
        res.status(500).send(error);
    }
})

router.get('/all', [requireRole("17th Administrator")], async (req: Request, res: Response) => {
    try {
        const page = Number(req.query.page) || undefined;
        const pageSize = Number(req.query.pageSize) || undefined;
        const result = await getAllLOA(page, pageSize);
        res.status(200).json(result)
    } catch (error) {
        console.error(error);
        res.status(500).send(error);
    }
})

router.get('/types', async (req: Request, res: Response) => {
    try {
        let out = await getLoaTypes();
        res.status(200).json(out);
    } catch (error) {
        res.status(500).json(error);
        console.error(error);
    }
})

router.post('/cancel/:id', async (req: Request, res: Response) => {
    let closer = req.user.id;
    let id = Number(req.params.id);
    try {
        let loa = await getLOAbyID(id);
        if (loa.member_id != closer) {
            return res.sendStatus(403);
        }

        await closeLOA(Number(req.params.id), closer);
        res.sendStatus(200);
    } catch (error) {
        console.error(error);
        res.status(500).json(error);
    }
})

//TODO: enforce admin only
router.post('/adminCancel/:id', [requireRole("17th Administrator")], async (req: Request, res: Response) => {
    let closer = req.user.id;
    try {
        await closeLOA(Number(req.params.id), closer);
        res.sendStatus(200);
    } catch (error) {
        console.error(error);
        res.status(500).json(error);
    }
})

// TODO: Enforce admin only
router.post('/extend/:id', [requireRole("17th Administrator")], async (req: Request, res: Response) => {
    const to: Date = req.body.to;

    if (!to) {
        res.status(400).send("Extension length is required");
    }

    try {
        await setLOAExtension(Number(req.params.id), to);
        res.sendStatus(200);
    } catch (error) {
        console.error(error)
        res.status(500).json(error);
    }
})

router.get('/policy', async (req: Request, res: Response) => {
    const output = await fetch(`${process.env.DOC_HOST}/api/pages/42`, {
        headers: {
            Authorization: `Token ${process.env.DOC_TOKEN_ID}:${process.env.DOC_TOKEN_SECRET}`,
        }
    })

    if (output.ok) {
        const out = await output.json();
        res.status(200).json(out.html);
    } else {
        console.error("Failed to fetch LOA policy from bookstack");
        res.sendStatus(500);
    }
})

export const loaRouter = router;