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

export const createApplicationRecord = async (req: Request, res: Response) => {
    try {
        const organizationId = req.appUser?.organizationId;
        const createdBy = req.appUser?.email || 'guest';
        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 record = await appRecordService.updateApplicationRecord(
            req.params.id as string,
            req.body
        );
        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 success = await appRecordService.deleteApplicationRecord(
            req.params.id as string
        );
        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 });
    }
};
