-- Invoices bill a User (not a Business). business_id remains tenant/context.

ALTER TABLE invoices
  ADD COLUMN IF NOT EXISTS user_id BIGINT;

-- Backfill: business owner, else any business_users row for that business
UPDATE invoices i
SET user_id = COALESCE(
  (
    SELECT bu.user_id
    FROM business_users bu
    WHERE bu.business_id = i.business_id
      AND bu.is_owner = TRUE
    ORDER BY bu.user_id
    LIMIT 1
  ),
  (
    SELECT bu.user_id
    FROM business_users bu
    WHERE bu.business_id = i.business_id
    ORDER BY bu.user_id
    LIMIT 1
  )
)
WHERE i.user_id IS NULL;

-- Drop any invoices that still have no resolvable user (orphan businesses)
DELETE FROM invoices WHERE user_id IS NULL;

ALTER TABLE invoices
  ALTER COLUMN user_id SET NOT NULL;

DO $$ BEGIN
  ALTER TABLE invoices
    ADD CONSTRAINT invoices_user_id_fkey
    FOREIGN KEY (user_id) REFERENCES users (id) ON DELETE RESTRICT;
EXCEPTION
  WHEN duplicate_object THEN NULL;
END $$;

CREATE INDEX IF NOT EXISTS idx_invoices_user_created
  ON invoices (user_id, created_at DESC);

CREATE INDEX IF NOT EXISTS idx_invoices_issuer_business_created
  ON invoices (issuer_business_id, created_at DESC)
  WHERE issuer_business_id IS NOT NULL;
