import { Request, Response } from 'express';
import * as projectService from '../services/projectService.js';
import { IAppUser } from '../middleware/authMiddleware.js';
import { notificationService } from '../services/notificationService.js';
import { toCamelCase } from '../utils/caseMapper.js';

interface AuthRequest extends Request {
    appUser?: IAppUser;
}

export const createProject = async (req: AuthRequest, res: Response) => {
    try {
        const organizationId = req.appUser?.organizationId;
        const project = await projectService.createProject({ ...req.body, organizationId });
        res.status(201).json(toCamelCase(project));
    } catch (error: any) {
        console.error('Error in createProject controller:', error);
        const message = error?.message || error?.details || (typeof error === 'string' ? error : JSON.stringify(error)) || 'Erro ao criar projeto';
        res.status(500).json({ error: message });
    }
};

export const getAllProjects = async (req: AuthRequest, res: Response) => {
    try {
        const organizationId = req.appUser?.organizationId;
        const isGlobalAdmin = req.appUser?.email === 'admtracksteel@gmail.com';
        const { status } = req.query;
        const projects = await projectService.getAllProjects(organizationId, isGlobalAdmin, status as string);
        res.json(toCamelCase(projects));
    } catch (error: any) {
        console.error('Error in getAllProjects controller:', error);
        const message = error?.message || error?.details || (typeof error === 'string' ? error : JSON.stringify(error));
        res.status(500).json({ error: message });
    }
};

export const archiveProject = async (req: AuthRequest, res: Response) => {
    try {
        const organizationId = req.appUser?.organizationId;
        const isGlobalAdmin = req.appUser?.email === 'admtracksteel@gmail.com';
        const project = await projectService.archiveProject(req.params.id as string, organizationId, isGlobalAdmin);
        res.json(toCamelCase(project));
    } catch (error: any) {
        const message = error?.message || error?.details || 'Erro ao arquivar projeto';
        res.status(500).json({ error: message });
    }
};

export const getDashboardProjects = async (req: AuthRequest, res: Response) => {
    try {
        const organizationId = req.appUser?.organizationId;
        const projects = await projectService.getDashboardProjects(organizationId);
        res.json(toCamelCase(projects));
    } catch (error: any) {
        const message = error?.message || error?.details || 'Erro ao obter projetos';
        res.status(500).json({ error: message });
    }
};

export const getProjectById = async (req: AuthRequest, res: Response) => {
    try {
        const project = await projectService.getProjectById(req.params.id as string);
        res.json(toCamelCase(project));
    } catch (error: any) {
        const message = error?.message || error?.details || 'Projeto não encontrado';
        res.status(404).json({ error: message });
    }
};

export const updateProject = async (req: AuthRequest, res: Response) => {
    try {
        const organizationId = req.appUser?.organizationId;
        const project = await projectService.updateProject(req.params.id as string, req.body);

        if (req.body.weightKg !== undefined && organizationId && project) {
            await notificationService.create({
                organizationId,
                title: 'Atualização de Obra',
                message: `O peso da obra "${project.name}" foi atualizado para ${project.weight_kg}kg.`,
                type: 'info',
                metadata: { projectId: project.id, triggerType: 'project_update' }
            });
        }

        res.json(toCamelCase(project));
    } catch (error: any) {
        const message = error?.message || error?.details || 'Erro ao atualizar projeto';
        res.status(500).json({ error: message });
    }
};

export const deleteProject = async (req: AuthRequest, res: Response) => {
    try {
        await projectService.deleteProject(req.params.id as string);
        res.status(204).send();
    } catch (error: any) {
        const message = error?.message || error?.details || 'Erro ao excluir projeto';
        res.status(500).json({ error: message });
    }
};