import { Request, Response } from 'express';
import * as inspectionService from '../services/inspectionService.js';
import { notificationService } from '../services/notificationService.js';
import { toCamelCase, toSnakeCase } from '../utils/caseMapper.js';

export const createInspection = async (req: Request, res: Response) => {
    try {
        const organizationId = req.appUser?.organizationId;
        const createdBy = req.appUser?.email || 'guest';
        
        const payload = toSnakeCase({
            ...req.body,
            organizationId,
            createdBy
        });

        const inspection = await inspectionService.createInspection(payload);

        if (req.body.appearance === 'rejected' && organizationId) {
            try {
                await notificationService.create({
                    organizationId,
                    title: 'Inspeção Reprovada',
                    message: `Uma inspeção foi reprovada na obra (ID: ${req.body.projectId}).`,
                    type: 'error',
                    metadata: { inspectionId: inspection?.id, projectId: req.body.projectId, triggerType: 'inspection_rejected' }
                });
            } catch (e) { /* ignore notification errors */ }
        }

        res.status(201).json(toCamelCase(inspection));
    } catch (error: unknown) {
        const message = error instanceof Error ? error.message : 'Unknown error';
        res.status(500).json({ error: message });
    }
};

export const getInspectionsByProject = async (req: Request, res: Response) => {
    try {
        const { projectId } = req.params;
        const organizationId = req.appUser?.organizationId;
        const inspections = await inspectionService.getInspectionsByProject(projectId as string, organizationId);
        res.json(toCamelCase(inspections || []));
    } catch (error: unknown) {
        res.json([]);
    }
};

export const updateInspection = async (req: Request, res: Response) => {
    try {
        const inspection = await inspectionService.updateInspection(
            req.params.id as string,
            toSnakeCase(req.body)
        );
        if (!inspection) return res.status(403).json({ error: 'Não autorizado ou não encontrado.' });
        res.json(toCamelCase(inspection));
    } catch (error: unknown) {
        const message = error instanceof Error ? error.message : 'Unknown error';
        res.status(500).json({ error: message });
    }
};

export const deleteInspection = async (req: Request, res: Response) => {
    try {
        await inspectionService.deleteInspection(req.params.id as string);
        res.status(204).send();
    } catch (error: unknown) {
        res.status(204).send();
    }
};

export const getAllInspections = async (req: Request, res: Response) => {
    try {
        const organizationId = req.appUser?.organizationId;
        const inspections = organizationId 
            ? await inspectionService.getInspectionsByOrganization(organizationId)
            : await inspectionService.getInspectionStats();
        res.json(toCamelCase(inspections || []));
    } catch (error: unknown) {
        res.json({ total: 0, inspections: [] });
    }
};

export const uploadPhoto = async (req: Request, res: Response) => {
    try {
        if (!req.file) {
            return res.status(400).json({ error: 'No file uploaded' });
        }
        const fileUrl = `/uploads/${req.file.filename}`;
        res.json({ url: fileUrl });
    } catch (error: unknown) {
        const message = error instanceof Error ? error.message : 'Unknown error';
        res.status(500).json({ error: message });
    }
};