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

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

export const createPaintingScheme = async (data: any) => {
    const orgId = data.organization_id || data.organizationId || DEFAULT_ORG_ID;
    const cleanPayload: any = {
        organization_id: orgId,
        project_id: data.project_id || data.projectId,
        name: data.name,
        type: data.type || null,
        coat: data.coat || null,
        solids_volume: data.solids_volume ?? data.solidsVolume ?? null,
        yield_theoretical: data.yield_theoretical ?? data.yieldTheoretical ?? null,
        eps_min: data.eps_min ?? data.epsMin ?? null,
        eps_max: data.eps_max ?? data.epsMax ?? null,
        dilution: data.dilution ?? null,
        manufacturer: data.manufacturer ?? null,
        color: data.color ?? null,
        color_hex: data.color_hex ?? data.colorHex ?? null,
        notes: data.notes ?? null,
        paint_consumption: data.paint_consumption ?? data.paintConsumption ?? null,
        thinner_consumption: data.thinner_consumption ?? data.thinnerConsumption ?? null,
        paint_id: data.paint_id ?? data.paintId ?? null,
        thinner_id: data.thinner_id ?? data.thinnerId ?? null,
        thinner_symbol: data.thinner_symbol ?? data.thinnerSymbol ?? null
    };

    // Remove any undefined properties
    Object.keys(cleanPayload).forEach(key => {
        if (cleanPayload[key] === undefined) {
            delete cleanPayload[key];
        }
    });

    const { data: scheme, error } = await supabase
        .from('painting_schemes')
        .insert(cleanPayload)
        .select()
        .single();
    if (error) {
        console.error('Error inserting painting scheme:', error);
        throw error;
    }
    return scheme;
};

export const getPaintingSchemesByProject = async (projectId: string, organizationId?: string) => {
    let query = supabase.from('painting_schemes').select('*').eq('project_id', projectId);
    const { data, error } = await query;
    if (error && error.code !== '42P01') throw error;
    return data || [];
};

export const getPaintingSchemeById = async (id: string) => {
    const { data, error } = await supabase.from('painting_schemes').select('*').eq('id', id).single();
    if (error && error.code !== '42P01') throw error;
    return data;
};

export const updatePaintingScheme = async (id: string, data: any, organizationId?: string) => {
    const cleanPayload: any = {
        ...(data.name !== undefined && { name: data.name }),
        ...(data.type !== undefined && { type: data.type }),
        ...(data.coat !== undefined && { coat: data.coat }),
        ...(data.solids_volume !== undefined && { solids_volume: data.solids_volume }),
        ...(data.solidsVolume !== undefined && { solids_volume: data.solidsVolume }),
        ...(data.yield_theoretical !== undefined && { yield_theoretical: data.yield_theoretical }),
        ...(data.yieldTheoretical !== undefined && { yield_theoretical: data.yieldTheoretical }),
        ...(data.eps_min !== undefined && { eps_min: data.eps_min }),
        ...(data.epsMin !== undefined && { eps_min: data.epsMin }),
        ...(data.eps_max !== undefined && { eps_max: data.eps_max }),
        ...(data.epsMax !== undefined && { eps_max: data.epsMax }),
        ...(data.dilution !== undefined && { dilution: data.dilution }),
        ...(data.manufacturer !== undefined && { manufacturer: data.manufacturer }),
        ...(data.color !== undefined && { color: data.color }),
        ...(data.color_hex !== undefined && { color_hex: data.color_hex }),
        ...(data.colorHex !== undefined && { color_hex: data.colorHex }),
        ...(data.notes !== undefined && { notes: data.notes }),
        ...(data.paint_consumption !== undefined && { paint_consumption: data.paint_consumption }),
        ...(data.paintConsumption !== undefined && { paint_consumption: data.paintConsumption }),
        ...(data.thinner_consumption !== undefined && { thinner_consumption: data.thinner_consumption }),
        ...(data.thinnerConsumption !== undefined && { thinner_consumption: data.thinnerConsumption }),
        ...(data.paint_id !== undefined && { paint_id: data.paint_id }),
        ...(data.paintId !== undefined && { paint_id: data.paintId }),
        ...(data.thinner_id !== undefined && { thinner_id: data.thinner_id }),
        ...(data.thinnerId !== undefined && { thinner_id: data.thinnerId }),
        ...(data.thinner_symbol !== undefined && { thinner_symbol: data.thinner_symbol }),
        ...(data.thinnerSymbol !== undefined && { thinner_symbol: data.thinnerSymbol }),
        updated_at: new Date().toISOString()
    };

    const { data: scheme, error } = await supabase
        .from('painting_schemes')
        .update(cleanPayload)
        .eq('id', id)
        .select()
        .single();
    if (error) {
        console.error('Error updating painting scheme:', error);
        throw error;
    }
    return scheme;
};

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

export const clonePaintingScheme = async (id: string, newData: any) => {
    const original = await getPaintingSchemeById(id);
    if (!original) return null;
    const { data: scheme, error } = await supabase
        .from('painting_schemes')
        .insert({ ...original, ...newData, id: undefined })
        .select()
        .single();
    if (error) throw error;
    return scheme;
};

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

