import { Request, Response, NextFunction } from 'express';
import { authenticateRequest } from './logtoAuth.js';
import { findOneGpi } from '../config/supabase.js';

export interface IAppUser {
    id: string;
    logtoId: string;
    email: string;
    name: string;
    role: string;
    organizationId?: string;
    organizationRole?: string;
}

declare module 'express-serve-static-core' {
    interface Request {
        appUser?: IAppUser;
    }
}

export const extractUser = async (req: Request, res: Response, next: NextFunction) => {
    try {
        const authHeader = req.headers.authorization;
        
        if (!authHeader?.startsWith('Bearer ')) {
            return next();
        }

        const user = await authenticateRequest(req);
        
        if (user) {
            req.appUser = user;
        }
        
        next();
    } catch (error) {
        console.error('Error extracting user:', error);
        next();
    }
};

export const requireRole = (allowedRoles: string[]) => {
    return (req: Request, res: Response, next: NextFunction) => {
        if (!req.appUser) {
            return res.status(401).json({ error: 'Autenticação necessária.' });
        }

        if (req.appUser.email === 'admtracksteel@gmail.com') {
            return next();
        }

        const effectiveRole = req.appUser.role;

        if (!allowedRoles.includes(effectiveRole)) {
            return res.status(403).json({ error: 'Acesso negado. Permissões insuficientes.' });
        }

        next();
    };
};

export const requireAdmin = requireRole(['admin']);
export const requireUser = requireRole(['user', 'admin']);

export const canEdit = (req: Request, res: Response, next: NextFunction) => {
    if (!req.appUser) {
        return res.status(401).json({ error: 'Autenticação necessária.' });
    }

    if (req.appUser.role === 'guest') {
        return res.status(403).json({ error: 'Convidados não podem editar.' });
    }

    next();
};

export const requireDeveloper = (req: Request, res: Response, next: NextFunction) => {
    if (!req.appUser) {
        return res.status(401).json({ error: 'Autenticação necessária.' });
    }

    if (req.appUser.email !== 'admtracksteel@gmail.com') {
        console.warn(`⛔ Attempted unauthorized developer access by: ${req.appUser.email}`);
        return res.status(403).json({ error: 'Acesso restrito ao desenvolvedor.' });
    }

    next();
};
