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

export const createInspection = async (req: Request, res: Response) => {
    try {
        const organizationId = req.appUser?.organizationId;
        const createdBy = req.appUser?.clerkId;
        const inspection = await inspectionService.createInspection({
            ...req.body,
            organizationId,
            createdBy
        });

        // Notificação de Inspeção Reprovada
        if (req.body.appearance === 'rejected' && organizationId) {
            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' }
            });
        }

        res.status(201).json(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(inspections);
    } catch (error: unknown) {
        const message = error instanceof Error ? error.message : 'Unknown error';
        res.status(500).json({ error: message });
    }
};

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

        const inspection = await inspectionService.updateInspection(
            req.params.id as string,
            req.body,
            organizationId,
            userId,
            userRole as any,
            isDeveloper
        );
        if (!inspection) return res.status(403).json({ error: 'Não autorizado ou não encontrado.' });
        res.json(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 {
        const organizationId = req.appUser?.organizationId;
        const userId = req.appUser?.clerkId;
        const userRole = req.appUser?.organizationRole || req.appUser?.role;
        const isDeveloper = req.appUser?.email === 'admtracksteel@gmail.com';

        const success = await inspectionService.deleteInspection(
            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 });
    }
};

export const getAllInspections = async (req: Request, res: Response) => {
    try {
        const organizationId = req.appUser?.organizationId;
        const inspections = await inspectionService.getAllInspections(organizationId);
        res.json(inspections);
    } catch (error: unknown) {
        const message = error instanceof Error ? error.message : 'Unknown error';
        res.status(500).json({ error: message });
    }
};

export const uploadPhoto = async (req: Request, res: Response) => {
    try {
        if (!req.file) {
            return res.status(400).json({ error: 'No file uploaded' });
        }

        // Return the public URL for the file
        // Assuming 'uploads' is served statically at /uploads
        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 });
    }
};
