import { supabase } from "@/integrations/supabase/client";

/**
 * AI bill parsing — calls the `parse-bill` Supabase Edge Function (ACMACC),
 * which uploads the file to Anthropic and returns structured fields.
 * Secret ANTHROPIC_API_KEY is configured as a Supabase Edge Function secret.
 */
export type ParsedBill = {
  bill_number?: string;
  bill_date?: string;
  due_date?: string;
  notes?: string;
  vendor_name?: string;
  subtotal?: number;
  tax_amount?: number;
  line_items?: Array<{ description?: string; quantity?: number; unit_price?: number; amount?: number }>;
};

export async function parseBill(input: { data: { fileUrl: string; mimeType: string } }): Promise<ParsedBill> {
  const { data, error } = await supabase.functions.invoke("parse-bill", {
    body: { fileUrl: input.data.fileUrl, mimeType: input.data.mimeType },
  });
  if (error) {
    // Supabase wraps non-2xx as FunctionsHttpError; surface the server message when present.
    const ctx: any = (error as any).context;
    let msg = error.message;
    try { const body = ctx && (await ctx.json?.()); if (body?.error) msg = body.error; } catch { /* ignore */ }
    throw new Error(msg || "AI bill parsing failed.");
  }
  if (data?.error) throw new Error(data.error);
  return (data ?? {}) as ParsedBill;
}
