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

export const createPaintingScheme = async (req: Request, res: Response) => {
    try {
        const organizationId = req.appUser?.organizationId || 'e47e6210-4879-4e5b-bf21-9285d2713123';
        const schemeData = toSnakeCase({ ...req.body, organizationId });
        const scheme = await paintingSchemeService.createPaintingScheme(schemeData);
        res.status(201).json(toCamelCase(scheme));
    } catch (error: any) {
        console.error('Error in createPaintingScheme:', error);
        res.status(400).json({ error: error?.message || error?.details || 'Erro ao cadastrar esquema de pintura' });
    }
};

export const getPaintingSchemesByProject = async (req: Request, res: Response) => {
    try {
        const { projectId } = req.params;
        const schemes = await paintingSchemeService.getPaintingSchemesByProject(projectId as string);
        res.json(toCamelCase(schemes || []));
    } catch (error: unknown) {
        res.json([]);
    }
};

export const updatePaintingScheme = async (req: Request, res: Response) => {
    try {
        const scheme = await paintingSchemeService.updatePaintingScheme(req.params.id as string, toSnakeCase(req.body));
        res.json(toCamelCase(scheme || req.body));
    } catch (error: unknown) {
        res.status(400).json({ error: (error as any).message });
    }
};

export const deletePaintingScheme = async (req: Request, res: Response) => {
    try {
        await paintingSchemeService.deletePaintingScheme(req.params.id as string);
        res.status(204).send();
    } catch (error: unknown) {
        res.status(500).json({ error: (error as any).message });
    }
};

export const getAllPaintingSchemes = async (req: Request, res: Response) => {
    try {
        const organizationId = req.appUser?.organizationId;
        const schemes = await paintingSchemeService.getAllSchemes(organizationId);
        res.json(toCamelCase(schemes || []));
    } catch (error: unknown) {
        res.json([]);
    }
};