import { Request, Response, NextFunction } from 'express';
import { authenticateRequest } from './logtoAuth.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;
    }
}

const DEFAULT_ORG_ID = 'e47e6210-4879-4e5b-bf21-9285d2713123';

const GUEST_USER: IAppUser = {
    id: '00000000-0000-0000-0000-000000000000',
    logtoId: 'guest',
    email: 'guest@gpi.app',
    name: 'Guest User',
    role: 'guest',
    organizationId: DEFAULT_ORG_ID,
    organizationRole: 'guest'
};

export const extractUser = async (req: Request, res: Response, next: NextFunction) => {
    try {
        const authenticatedUser = await authenticateRequest(req);
        if (authenticatedUser) {
            req.appUser = {
                ...authenticatedUser,
                organizationId: req.headers['x-organization-id'] as string || DEFAULT_ORG_ID,
                organizationRole: authenticatedUser.role
            };
        } else {
            req.appUser = {
                ...GUEST_USER,
                organizationId: req.headers['x-organization-id'] as string || DEFAULT_ORG_ID,
            };
        }
    } catch {
        req.appUser = {
            ...GUEST_USER,
            organizationId: req.headers['x-organization-id'] as string || DEFAULT_ORG_ID,
        };
    }
    next();
};

export const requireRole = (allowedRoles: string[]) => {
    return (req: Request, res: Response, next: NextFunction) => {
        if (!req.appUser || !allowedRoles.includes(req.appUser.role)) {
            return res.status(403).json({ error: 'Acesso negado. Permissão insuficiente.' });
        }
        next();
    };
};

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

export const canEdit = (req: Request, res: Response, next: NextFunction) => {
    if (!req.appUser || req.appUser.role === 'guest') {
        return res.status(403).json({ error: 'Convidados não podem editar. Faça login para ter acesso completo.' });
    }
    next();
};

export const requireDeveloper = (req: Request, res: Response, next: NextFunction) => {
    const isDev = req.appUser && (
        req.appUser.email === 'admtracksteel@gmail.com' ||
        req.appUser.role === 'admin' ||
        req.appUser.id === 'admin-user' ||
        req.appUser.id === 'c0eebc99-9c0b-4ef8-bb6d-6bb9bd380a10' ||
        req.appUser.logtoId === 'admin'
    );
    if (!isDev) {
        return res.status(403).json({ error: 'Acesso restrito ao desenvolvedor.' });
    }
    next();
};
