import { Request, Response } from 'express'; import * as inspectionService from '../services/inspectionService.js'; import { notificationService } from '../services/notificationService.js'; export const createInspection = async (req: Request, res: Response) => { try { const organizationId = req.appUser?.organizationId; const createdBy = req.appUser?.email || 'guest'; const inspection = await inspectionService.createInspection({ ...req.body, organizationId, createdBy }); 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(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) { res.json([]); } }; export const updateInspection = async (req: Request, res: Response) => { try { const inspection = await inspectionService.updateInspection( req.params.id as string, req.body ); 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 success = 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(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 }); } };