// db.jsx — Database layer con Supabase

// Helper: obtener user_id actual
const getUserId = () => {
  const user = supabase.auth.getUser();
  return user?.id;
};

// === CLIENTS ===
const loadClients = async () => {
  const { data, error } = await supabase.from('clients').select('*').order('name');
  if (error) {
    console.error('Error loading clients:', error);
    return [];
  }
  return data;
};

const saveClient = async (client) => {
  const userId = getUserId();
  if (!userId) throw new Error('Not authenticated');
  
  const payload = { ...client, user_id: userId };
  if (client.id) {
    // Update
    const { data, error } = await supabase.from('clients').update(payload).eq('id', client.id);
    if (error) throw error;
    return data[0];
  } else {
    // Insert
    delete payload.id;
    const { data, error } = await supabase.from('clients').insert([payload]);
    if (error) throw error;
    return data[0];
  }
};

const deleteClient = async (id) => {
  const { error } = await supabase.from('clients').delete().eq('id', id);
  if (error) throw error;
};

// === SERVICES ===
const loadServices = async () => {
  const { data, error } = await supabase.from('services').select('*').order('name');
  if (error) {
    console.error('Error loading services:', error);
    return [];
  }
  return data;
};

const saveService = async (service) => {
  const userId = getUserId();
  if (!userId) throw new Error('Not authenticated');
  
  const payload = { ...service, user_id: userId };
  if (service.id) {
    const { data, error } = await supabase.from('services').update(payload).eq('id', service.id);
    if (error) throw error;
    return data[0];
  } else {
    delete payload.id;
    const { data, error } = await supabase.from('services').insert([payload]);
    if (error) throw error;
    return data[0];
  }
};

// === INVOICES ===
const loadInvoices = async () => {
  const { data, error } = await supabase.from('invoices').select('*').order('issued', { ascending: false });
  if (error) {
    console.error('Error loading invoices:', error);
    return [];
  }
  return data;
};

const saveInvoice = async (invoice) => {
  const userId = getUserId();
  if (!userId) throw new Error('Not authenticated');
  
  const payload = { ...invoice, user_id: userId };
  if (invoice.id) {
    const { data, error } = await supabase.from('invoices').update(payload).eq('id', invoice.id);
    if (error) throw error;
    return data[0];
  } else {
    delete payload.id;
    const { data, error } = await supabase.from('invoices').insert([payload]);
    if (error) throw error;
    return data[0];
  }
};

const deleteInvoice = async (id) => {
  const { error } = await supabase.from('invoices').delete().eq('id', id);
  if (error) throw error;
};

const markInvoicePaid = async (id) => {
  const { data, error } = await supabase.from('invoices')
    .update({ status: 'paid', paid_at: new Date().toISOString() })
    .eq('id', id);
  if (error) throw error;
  return data[0];
};

const markInvoiceSent = async (id) => {
  const { data, error } = await supabase.from('invoices')
    .update({ status: 'pending', sent_at: new Date().toISOString() })
    .eq('id', id);
  if (error) throw error;
  return data[0];
};

// === SEED DATA (primera vez) ===
const seedInitialData = async () => {
  const userId = getUserId();
  if (!userId) return;

  // Check si ya tiene datos
  const { data: existingClients } = await supabase.from('clients').select('id').limit(1);
  if (existingClients && existingClients.length > 0) return; // ya tiene datos

  console.log('🌱 Seeding initial data...');

  // Seed clients
  const clientsToSeed = [
    { name: "Northstar Architects", contact: "Priya Anand", email: "priya@northstar-arch.com", city: "Seattle, WA", color: "oklch(0.72 0.12 145)" },
    { name: "Meridian Construction Group", contact: "Daniel Cho", email: "dcho@meridiancg.com", city: "Austin, TX", color: "oklch(0.72 0.12 220)" },
    { name: "Atlas Engineering", contact: "Rosa Vidal", email: "rvidal@atlas-eng.com", city: "Denver, CO", color: "oklch(0.72 0.12 60)" },
  ];
  
  for (const c of clientsToSeed) {
    await supabase.from('clients').insert([{ ...c, user_id: userId }]);
  }

  // Seed services
  const servicesToSeed = [
    { code: "BIM-MOD-LOD350", name: "Revit Modeling — LOD 350", rate: 145, unit: "hr" },
    { code: "BIM-COORD", name: "BIM Coordination & Clash Detection", rate: 165, unit: "hr" },
    { code: "SCAN-TO-BIM", name: "Scan-to-BIM (Point cloud)", rate: 185, unit: "hr" },
    { code: "4D-SIM", name: "4D Construction Sequencing", rate: 195, unit: "hr" },
    { code: "BIM-MGT", name: "BIM Management Consulting", rate: 220, unit: "hr" },
  ];

  for (const s of servicesToSeed) {
    await supabase.from('services').insert([{ ...s, user_id: userId }]);
  }

  console.log('✅ Seed complete');
};

Object.assign(window, {
  loadClients,
  saveClient,
  deleteClient,
  loadServices,
  saveService,
  loadInvoices,
  saveInvoice,
  deleteInvoice,
  markInvoicePaid,
  markInvoiceSent,
  seedInitialData,
});
