-- Migration 012: Replace 'sent' status with 'pending' for invoices
-- 'sent' implied email delivery which doesn't exist; 'pending' is more accurate

DO $$
DECLARE
  v_schema TEXT;
  v_constraint TEXT;
BEGIN
  FOR v_schema IN
    SELECT schema_name FROM information_schema.schemata
    WHERE schema_name LIKE 'tenant_%'
  LOOP
    -- Find and drop the existing status check constraint
    SELECT constraint_name INTO v_constraint
    FROM information_schema.table_constraints
    WHERE table_schema = v_schema
      AND table_name = 'invoices'
      AND constraint_type = 'CHECK'
      AND constraint_name LIKE '%status%';

    IF v_constraint IS NOT NULL THEN
      EXECUTE format('ALTER TABLE %I.invoices DROP CONSTRAINT %I', v_schema, v_constraint);
    END IF;

    -- Add new constraint that includes 'pending'
    EXECUTE format('ALTER TABLE %I.invoices ADD CONSTRAINT invoices_status_check CHECK (status IN (
      ''draft'', ''pending'', ''sent'', ''paid'', ''partial'', ''overdue'', ''void'', ''written_off''
    ))', v_schema);

    -- Convert existing 'sent' invoices to 'pending'
    EXECUTE format('UPDATE %I.invoices SET status = ''pending'' WHERE status = ''sent''', v_schema);
  END LOOP;
END $$;
