"use server";

import { createClient } from "@/lib/supabase/server";
import { revalidatePath } from "next/cache";

export async function getServices() {
  const supabase = await createClient();
  const { data, error } = await supabase.from("services_catalog").select("*").eq("is_active", true).order("name");
  if (error) throw error;
  return data;
}

export async function createService(formData: FormData) {
  const supabase = await createClient();
  const { data: { user } } = await supabase.auth.getUser();
  if (!user) throw new Error("No autenticado");
  const { data: profile } = await supabase.from("users").select("clinic_id").eq("id", user.id).single();
  if (!profile) throw new Error("Perfil no encontrado");

  const { error } = await supabase.from("services_catalog").insert({
    clinic_id: profile.clinic_id,
    name: formData.get("name") as string,
    description: (formData.get("description") as string) || null,
    price: parseFloat(formData.get("price") as string) || 0,
    sat_product_key: (formData.get("sat_product_key") as string) || null,
    sat_unit_key: (formData.get("sat_unit_key") as string) || "E48",
    tax_rate: parseFloat(formData.get("tax_rate") as string) || 0.16,
  });
  if (error) throw error;
  revalidatePath("/billing");
}

export async function getInvoices(status?: string) {
  const supabase = await createClient();
  let query = supabase
    .from("invoices")
    .select("*, patient:patients(id, first_name, last_name)")
    .order("created_at", { ascending: false })
    .limit(50);
  if (status && status !== "all") query = query.eq("payment_status", status);
  const { data, error } = await query;
  if (error) throw error;
  return data;
}

export async function getInvoice(id: string) {
  const supabase = await createClient();
  const { data, error } = await supabase
    .from("invoices")
    .select("*, patient:patients(id, first_name, last_name, rfc:curp, email, phone), items:invoice_items(*)")
    .eq("id", id).single();
  if (error) throw error;
  return data;
}

export async function createInvoice(data: {
  patient_id: string;
  items: { description: string; quantity: number; unit_price: number; tax_rate: number; service_id?: string; product_id?: string }[];
  forma_pago?: string;
  metodo_pago?: string;
  uso_cfdi?: string;
}) {
  const supabase = await createClient();
  const { data: { user } } = await supabase.auth.getUser();
  if (!user) throw new Error("No autenticado");
  const { data: profile } = await supabase.from("users").select("clinic_id").eq("id", user.id).single();
  if (!profile) throw new Error("Perfil no encontrado");

  // Generate invoice number
  const { count } = await supabase.from("invoices").select("*", { count: "exact", head: true }).eq("clinic_id", profile.clinic_id);
  const invoiceNumber = `F-${String((count || 0) + 1).padStart(5, "0")}`;

  const subtotal = data.items.reduce((sum, i) => sum + i.quantity * i.unit_price, 0);
  const taxAmount = data.items.reduce((sum, i) => sum + i.quantity * i.unit_price * i.tax_rate, 0);

  const { data: invoice, error: invoiceError } = await supabase.from("invoices").insert({
    clinic_id: profile.clinic_id,
    patient_id: data.patient_id,
    invoice_number: invoiceNumber,
    subtotal: Math.round(subtotal * 100) / 100,
    tax_amount: Math.round(taxAmount * 100) / 100,
    total: Math.round((subtotal + taxAmount) * 100) / 100,
    forma_pago: data.forma_pago || "01",
    metodo_pago: data.metodo_pago || "PUE",
    uso_cfdi: data.uso_cfdi || "S01",
    created_by: user.id,
  }).select().single();

  if (invoiceError) throw invoiceError;

  const items = data.items.map(i => ({
    invoice_id: invoice.id,
    description: i.description,
    quantity: i.quantity,
    unit_price: i.unit_price,
    tax_rate: i.tax_rate,
    total: Math.round(i.quantity * i.unit_price * (1 + i.tax_rate) * 100) / 100,
    service_id: i.service_id || null,
    product_id: i.product_id || null,
  }));

  const { error: itemsError } = await supabase.from("invoice_items").insert(items);
  if (itemsError) throw itemsError;

  revalidatePath("/billing");
  return invoice;
}

export async function recordPayment(invoiceId: string, amount: number, method: string, reference?: string) {
  const supabase = await createClient();
  const { data: { user } } = await supabase.auth.getUser();
  if (!user) throw new Error("No autenticado");
  const { data: profile } = await supabase.from("users").select("clinic_id").eq("id", user.id).single();
  if (!profile) throw new Error("Perfil no encontrado");

  await supabase.from("payments").insert({
    clinic_id: profile.clinic_id,
    invoice_id: invoiceId,
    amount,
    payment_method: method,
    reference: reference || null,
    received_by: user.id,
  });

  // Update invoice paid amount
  const { data: invoice } = await supabase.from("invoices").select("total, paid_amount").eq("id", invoiceId).single();
  if (invoice) {
    const newPaid = (invoice.paid_amount || 0) + amount;
    const status = newPaid >= invoice.total ? "paid" : "partial";
    await supabase.from("invoices").update({ paid_amount: newPaid, payment_status: status }).eq("id", invoiceId);
  }

  revalidatePath("/billing");
}
