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

interface AuthRequest extends Request {
    appUser?: IAppUser;
}

export const createProject = async (req: AuthRequest, res: Response) => {
    try {
        console.log('Backend creating project. Body:', req.body);
        const organizationId = req.appUser?.organizationId;
        const project = await projectService.createProject({ ...req.body, organizationId });
        console.log('Project created successfully:', project._id);
        res.status(201).json(project);
    } catch (error: unknown) {
        const message = error instanceof Error ? error.message : 'Unknown error';
        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(projects);
    } catch (error: unknown) {
        const message = error instanceof Error ? error.message : 'Unknown 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(project);
    } catch (error: unknown) {
        const message = error instanceof Error ? error.message : 'Unknown error';
        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(projects);
    } catch (error: unknown) {
        const message = error instanceof Error ? error.message : 'Unknown error';
        res.status(500).json({ error: message });
    }
};

export const getProjectById = async (req: AuthRequest, res: Response) => {
    try {
        const organizationId = req.appUser?.organizationId;
        const isGlobalAdmin = req.appUser?.email === 'admtracksteel@gmail.com';
        const project = await projectService.getProjectById(req.params.id as string, organizationId, isGlobalAdmin);
        res.json(project);
    } catch (error: unknown) {
        const message = error instanceof Error ? error.message : 'Unknown error';
        res.status(404).json({ error: message });
    }
};

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

        // Notificação se Peso mudar (Exemplo simplificado, idealmente compararíamos com valor anterior)
        // Como o update retorna o objeto atualizado, podemos assumir que se o body tem weightKg, houve intenção de mudar.
        // Para ser mais preciso, deveríamos buscar o antigo antes, mas para MVP vamos notificar se houver o campo no body.
        if (req.body.weightKg !== undefined && organizationId) {
            await notificationService.create({
                organizationId,
                title: 'Atualização de Obra',
                message: `O peso da obra "${project.name}" foi atualizado para ${project.weightKg}kg.`,
                type: 'info',
                metadata: { projectId: project._id, triggerType: 'project_update' }
            });
        }

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

export const deleteProject = async (req: AuthRequest, res: Response) => {
    try {
        const organizationId = req.appUser?.organizationId;
        const isGlobalAdmin = req.appUser?.email === 'admtracksteel@gmail.com';
        await projectService.deleteProject(req.params.id as string, organizationId, isGlobalAdmin);
        res.status(204).send();
    } catch (error: unknown) {
        const message = error instanceof Error ? error.message : 'Unknown error';
        res.status(500).json({ error: message });
    }
};
