import { NextFunction, Request, Response } from "express";
import { CustomRequest } from "../types/custom.types";
import { auth } from "firebase-admin";
import firebaseApp from "../config/firebase.config";
import createHttpError from "http-errors";
import Authority from "../models/authority.model";
import { STATE } from "../types/common.types";

export default class AuthMiddleware {
    static includeToken(req: CustomRequest, res: Response, next: NextFunction) {
        const token = String(req.headers.authorization || '').split("Bearer ")?.[1];
        req.accessToken = token;
        next();
    }

    static async includeUser(req: CustomRequest, res: Response, next: NextFunction) {
        try {
            if (!req.accessToken) return next();
            const user = await auth(firebaseApp).verifyIdToken(req.accessToken);
            req.user = user;
            next();
        } catch (error) {
            console.error(error)
            next();
        }
    }
    static async verified(req: CustomRequest, res: Response, next: NextFunction) {
        return next(req?.user?.uid ? null : createHttpError.Unauthorized('Login to get access.'))
    }
    static async includeAuthority(req: CustomRequest, res: Response, next: NextFunction) {
        try {
            const email = req?.user?.email;
            if(email){
                const authority = await Authority.findOne({
                    where: {
                        email: email,
                        status: STATE.ACTIVE
                    }
                });
                req.authority = authority?.dataValues || undefined;
            }
            next();
        } catch (error) {
            next();
        }
    }
    static async authority(req: CustomRequest, res: Response, next: NextFunction) {
        try {
            const email = req?.user?.email;
            const authority = await Authority.findOne({
                where: {
                    email: email,
                    status: STATE.ACTIVE
                }
            });
            if (!authority?.dataValues?.id) throw createHttpError.BadRequest("You don't have access.");
            else next();
        } catch (error) {
            next(error)
        }
    }
}