import { Request, Response } from 'express';
import * as appRecordService from '../services/applicationRecordService.js';
import '../middleware/roleMiddleware.js'; // Ensure type augmentation

export const createApplicationRecord = async (req: Request, res: Response) => {
    try {
        const organizationId = req.appUser?.organizationId;
        const createdBy = req.appUser?.externalId;
        const record = await appRecordService.createApplicationRecord({ ...req.body, organizationId, createdBy });
        res.status(201).json(record);
    } catch (error: unknown) {
        const message = error instanceof Error ? error.message : 'Unknown error';
        res.status(500).json({ error: message });
    }
};

export const getApplicationRecordsByProject = async (req: Request, res: Response) => {
    try {
        const { projectId } = req.params;
        const organizationId = req.appUser?.organizationId;
        const records = await appRecordService.getApplicationRecordsByProject(projectId as string, organizationId);
        res.json(records);
    } catch (error: unknown) {
        const message = error instanceof Error ? error.message : 'Unknown error';
        res.status(500).json({ error: message });
    }
};

export const updateApplicationRecord = async (req: Request, res: Response) => {
    try {
        const organizationId = req.appUser?.organizationId;
        const userId = req.appUser?.externalId;
        const userRole = req.appUser?.organizationRole || req.appUser?.role;
        const isDeveloper = req.appUser?.email === 'admtracksteel@gmail.com';

        const record = await appRecordService.updateApplicationRecord(
            req.params.id as string,
            req.body,
            organizationId,
            userId,
            userRole as any,
            isDeveloper
        );
        if (!record) return res.status(403).json({ error: 'Não autorizado ou não encontrado.' });
        res.json(record);
    } catch (error: unknown) {
        const message = error instanceof Error ? error.message : 'Unknown error';
        res.status(500).json({ error: message });
    }
};

export const deleteApplicationRecord = async (req: Request, res: Response) => {
    try {
        const organizationId = req.appUser?.organizationId;
        const userId = req.appUser?.externalId;
        const userRole = req.appUser?.organizationRole || req.appUser?.role;
        const isDeveloper = req.appUser?.email === 'admtracksteel@gmail.com';

        const success = await appRecordService.deleteApplicationRecord(
            req.params.id as string,
            organizationId,
            userId,
            userRole as any,
            isDeveloper
        );
        if (!success) return res.status(403).json({ error: 'Não autorizado ou não encontrado.' });
        res.status(204).send();
    } catch (error: unknown) {
        const message = error instanceof Error ? error.message : 'Unknown error';
        res.status(500).json({ error: message });
    }
};
