import { supabase } from '../config/supabase.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 { data: project, error } = await supabase
        .from('projects')
        .insert({
            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'
        })
        .select()
        .single();

    if (error) throw error;
    return project;
};

export const getAllProjects = async (organizationId?: string, isGlobalAdmin?: boolean, status?: string) => {
    try {
        let query = supabase
            .from('projects')
            .select('*, painting_schemes(*)');
        
        if (status) {
            query = query.eq('status', status);
        }

        const { data: projects, error } = await query;
        
        if (error) {
            console.log('Error fetching projects:', error);
            return [];
        }
        
        return projects || [];
    } catch (error) {
        console.error('Error getting projects:', error);
        return [];
    }
};

export const getDashboardProjects = async (organizationId?: string) => {
    try {
        const { data: projects, error } = await supabase
            .from('projects')
            .select('*, painting_schemes(*)');
        
        if (error) return [];
        return projects || [];
    } catch (error) {
        console.error('Error getting dashboard projects:', error);
        return [];
    }
};

export const archiveProject = async (id: string, organizationId?: string, isGlobalAdmin?: boolean) => {
    const { data: project, error: fetchError } = await supabase
        .from('projects')
        .select('*')
        .eq('id', id)
        .single();
        
    if (fetchError || !project) throw new Error('Projeto não encontrado');
    
    if (!isGlobalAdmin && project.organization_id !== organizationId) {
        throw new Error('Acesso negado');
    }
    
    const { data: updated, error } = await supabase
        .from('projects')
        .update({ status: 'archived' })
        .eq('id', id)
        .select()
        .single();
        
    if (error) throw error;
    return updated;
};

export const getProjectById = async (id: string) => {
    const { data, error } = await supabase
        .from('projects')
        .select('*, painting_schemes(*)')
        .eq('id', id)
        .single();
        
    if (error) throw error;
    return data;
};

export const updateProject = async (id: string, data: Partial<ProjectData> & { organizationId?: string }) => {
    const updateData: any = { ...data };
    delete updateData.organizationId;
    
    if (data.startDate !== undefined) {
        updateData.start_date = data.startDate ? new Date(data.startDate).toISOString() : null;
        delete updateData.startDate;
    }
    if (data.endDate !== undefined) {
        updateData.end_date = data.endDate ? new Date(data.endDate).toISOString() : null;
        delete updateData.endDate;
    }
    if (data.weightKg !== undefined) {
        updateData.weight_kg = data.weightKg;
        delete updateData.weightKg;
    }
    
    const { data: updated, error } = await supabase
        .from('projects')
        .update(updateData)
        .eq('id', id)
        .select()
        .single();
        
    if (error) throw error;
    return updated;
};

export const deleteProject = async (id: string) => {
    const { error } = await supabase
        .from('projects')
        .delete()
        .eq('id', id);
        
    if (error) throw error;
};

export const getProjectStats = async (projectId: string) => {
    const { data: project, error: projectError } = await supabase
        .from('projects')
        .select('*')
        .eq('id', projectId)
        .single();
        
    if (projectError || !project) return null;
    
    const [schemesRes, inspectionsRes, partsRes] = await Promise.all([
        supabase.from('painting_schemes').select('*').eq('project_id', projectId),
        supabase.from('inspections').select('*').eq('project_id', projectId),
        supabase.from('parts').select('*').eq('project_id', projectId)
    ]);
    
    return {
        project,
        schemes: schemesRes.data || [],
        inspections: inspectionsRes.data || [],
        parts: partsRes.data || []
    };
};