ALTER TABLE public.invoices
ADD COLUMN IF NOT EXISTS line_items jsonb NOT NULL DEFAULT '[]'::jsonb,
ADD COLUMN IF NOT EXISTS raw_pdf_url text;

ALTER TABLE public.bills
ADD COLUMN IF NOT EXISTS source_invoice_id uuid;

DO $$
BEGIN
  IF NOT EXISTS (
    SELECT 1
    FROM pg_constraint
    WHERE conname = 'bills_source_invoice_id_fkey'
      AND conrelid = 'public.bills'::regclass
  ) THEN
    ALTER TABLE public.bills
    ADD CONSTRAINT bills_source_invoice_id_fkey
    FOREIGN KEY (source_invoice_id)
    REFERENCES public.invoices(id)
    ON DELETE SET NULL;
  END IF;
END $$;

UPDATE public.bills b
SET source_invoice_id = linked.invoice_id
FROM (
  SELECT DISTINCT ON (bill_id) bill_id, invoice_id
  FROM public.bill_approvals
  WHERE bill_id IS NOT NULL AND invoice_id IS NOT NULL
  ORDER BY bill_id, created_at ASC
) AS linked
WHERE b.id = linked.bill_id
  AND b.source_invoice_id IS NULL;

CREATE INDEX IF NOT EXISTS idx_bills_source_invoice_id ON public.bills(source_invoice_id);
CREATE UNIQUE INDEX IF NOT EXISTS idx_bills_source_invoice_id_unique ON public.bills(source_invoice_id) WHERE source_invoice_id IS NOT NULL;