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

export const createPaintingScheme = async (data: any & { organizationId?: string }) => {
    const { data: scheme, error } = await supabase
        .from('painting_schemes')
        .insert({ ...data, organization_id: data.organizationId })
        .select()
        .single();
    if (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 { data: scheme, error } = await supabase
        .from('painting_schemes')
        .update(data)
        .eq('id', id)
        .select()
        .single();
    if (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 || [];
};

