-- 044: Compliance orders — tracks paid compliance service orders
--
-- Bridges the gap between the free compliance check tool and ERPNext:
--   1. Customer runs free compliance check → sees what needs fixing
--   2. Customer places a compliance order → creates row here
--   3. Checkout creates Stripe session → payment_status advances
--   4. On payment: ERPNext Sales Order created, webhook triggers worker
--   5. Worker generates documents, uploads to MinIO
--   6. Delivery worker emails documents to customer

CREATE TABLE IF NOT EXISTS compliance_orders (
    id              SERIAL PRIMARY KEY,
    order_number    TEXT NOT NULL UNIQUE,       -- CO-XXXXXXXX format
    -- Service
    service_slug    TEXT NOT NULL,              -- maps to SERVICE_HANDLERS key
    service_name    TEXT NOT NULL,              -- human-readable service name
    service_fee_cents INTEGER NOT NULL DEFAULT 0,
    -- Linked entity (optional — required for FCC services)
    telecom_entity_id INTEGER REFERENCES telecom_entities(id),
    -- Customer
    customer_email  TEXT NOT NULL,
    customer_name   TEXT NOT NULL,
    customer_phone  TEXT,
    -- Payment
    payment_status  TEXT NOT NULL DEFAULT 'pending_payment'
                    CHECK (payment_status IN (
                        'pending_payment', 'paid', 'refunded', 'cancelled'
                    )),
    payment_method  TEXT,
    surcharge_pct   NUMERIC(5,2) DEFAULT 0,
    surcharge_cents  INTEGER DEFAULT 0,
    stripe_session_id TEXT,
    paid_at         TIMESTAMPTZ,
    -- Discount
    discount_code   TEXT,
    discount_cents  INTEGER DEFAULT 0,
    -- ERPNext link
    erpnext_sales_order TEXT,
    -- Metadata
    notes           TEXT,
    intake_data     JSONB DEFAULT '{}',        -- questionnaire answers, entity snapshot
    created_at      TIMESTAMPTZ DEFAULT NOW(),
    updated_at      TIMESTAMPTZ DEFAULT NOW()
);

CREATE INDEX IF NOT EXISTS idx_compliance_orders_email ON compliance_orders(customer_email);
CREATE INDEX IF NOT EXISTS idx_compliance_orders_entity ON compliance_orders(telecom_entity_id)
    WHERE telecom_entity_id IS NOT NULL;
CREATE INDEX IF NOT EXISTS idx_compliance_orders_status ON compliance_orders(payment_status);
