import { supabase } from '../config/supabase.js';

const DEFAULT_ORG_ID = 'e47e6210-4879-4e5b-bf21-9285d2713123';

export const createInspection = async (data: any) => {
    const orgId = data.organization_id || data.organizationId || DEFAULT_ORG_ID;
    const { data: inspection, error } = await supabase
        .from('inspections')
        .insert({
            ...data,
            date: data.date ? new Date(data.date).toISOString() : null,
            organization_id: orgId,
            created_by: data.createdBy || data.created_by
        })
        .select()
        .single();

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

export const getInspectionsByProject = async (projectId: string, organizationId?: string) => {
    let query = supabase
        .from('inspections')
        .select('*')
        .eq('project_id', projectId);

    if (organizationId) {
        query = query.eq('organization_id', organizationId);
    }

    const { data, error } = await query;
    
    if (error && error.code !== '42P01') throw error;
    return data || [];
};

export const getInspectionById = async (id: string) => {
    const { data, error } = await supabase
        .from('inspections')
        .select('*')
        .eq('id', id)
        .single();

    if (error && error.code !== '42P01') throw error;
    return data;
};

export const updateInspection = async (id: string, data: any) => {
    const { data: inspection, error } = await supabase
        .from('inspections')
        .update(data)
        .eq('id', id)
        .select()
        .single();

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

export const deleteInspection = async (id: string) => {
    const { error } = await supabase
        .from('inspections')
        .delete()
        .eq('id', id);

    if (error) throw error;
};

export const getInspectionsByOrganization = async (organizationId: string) => {
    const { data, error } = await supabase
        .from('inspections')
        .select('*')
        .eq('organization_id', organizationId);

    if (error && error.code !== '42P01') throw error;
    return data || [];
};

export const getInspectionStats = async (organizationId?: string) => {
    let query = supabase.from('inspections').select('*');
    
    if (organizationId) {
        query = query.eq('organization_id', organizationId);
    }
    
    const { data, error } = await query;
    
    if (error && error.code !== '42P01') {
        return { total: 0, inspections: [] };
    }
    
    return {
        total: data?.length || 0,
        inspections: data || []
    };
};

