import { 
    Project, Part, PaintingScheme, ApplicationRecord, Inspection,
    supabase, findOneGpi, queryGpi 
} from '../lib/compat.js';

interface ProjectData {
    name: string;
    client: string;
    startDate?: string | Date;
    endDate?: string | Date;
    technician?: string;
    environment?: string;
    weightKg?: number;
}

export const createProject = async (data: ProjectData & { organizationId?: string }) => {
    const project = await Project.create({
        name: data.name,
        client: data.client,
        start_date: data.startDate ? new Date(data.startDate).toISOString() : null,
        end_date: data.endDate ? new Date(data.endDate).toISOString() : null,
        technician: data.technician,
        environment: data.environment,
        organization_id: data.organizationId,
        weight_kg: data.weightKg,
        status: 'active'
    });
    return project;
};

export const getAllProjects = async (organizationId?: string, isGlobalAdmin?: boolean, status?: string) => {
    const filter: any = {};
    if (organizationId && !isGlobalAdmin) {
        filter.organization_id = organizationId;
    }
    if (status) {
        filter.status = status;
    }
    return await Project.find(filter);
};

export const getDashboardProjects = async (organizationId?: string) => {
    const filter: any = organizationId ? { organization_id: organizationId } : {};
    return await Project.find(filter);
};

export const archiveProject = async (id: string, organizationId?: string, isGlobalAdmin?: boolean) => {
    const project = await Project.findById(id);
    if (!project) throw new Error('Projeto não encontrado');
    
    if (!isGlobalAdmin && project.organization_id !== organizationId) {
        throw new Error('Acesso negado');
    }
    
    return await Project.findByIdAndUpdate(id, { status: 'archived' });
};

export const getProjectById = async (id: string) => {
    return await Project.findById(id);
};

export const updateProject = async (id: string, data: Partial<ProjectData>) => {
    return await Project.findByIdAndUpdate(id, data);
};

export const deleteProject = async (id: string) => {
    return await Project.findByIdAndDelete(id);
};

export const getProjectStats = async (projectId: string) => {
    const project = await Project.findById(projectId);
    if (!project) return null;
    
    const schemes = await PaintingScheme.find({ project_id: projectId });
    const inspections = await Inspection.find({ project_id: projectId });
    const parts = await Part.find({ project_id: projectId });
    
    return {
        project,
        schemesCount: schemes.length,
        inspectionsCount: inspections.length,
        partsCount: parts.length
    };
};

console.log('✅ ProjectService loaded with compatibility layer');
