-- Migration 136: Simply CRM subscription staging (parking area)
-- Import recurring SalesOrders into staging, then approve per customer.

CREATE TABLE IF NOT EXISTS simply_subscription_staging (
    id SERIAL PRIMARY KEY,
    source_system VARCHAR(50) NOT NULL DEFAULT 'simplycrm',
    source_record_id VARCHAR(64) NOT NULL,
    source_account_id VARCHAR(64),
    source_customer_name VARCHAR(255),
    source_customer_cvr VARCHAR(32),
    source_salesorder_no VARCHAR(100),
    source_subject TEXT,
    source_status VARCHAR(50),
    source_start_date DATE,
    source_end_date DATE,
    source_binding_end_date DATE,
    source_billing_frequency VARCHAR(50),
    source_total_amount NUMERIC(12,2) DEFAULT 0,
    source_currency VARCHAR(10) DEFAULT 'DKK',
    source_raw JSONB NOT NULL,
    sync_hash VARCHAR(64),

    hub_customer_id INTEGER REFERENCES customers(id) ON DELETE SET NULL,
    hub_sag_id INTEGER REFERENCES sag_sager(id) ON DELETE SET NULL,

    approval_status VARCHAR(20) NOT NULL DEFAULT 'pending'
        CHECK (approval_status IN ('pending', 'mapped', 'approved', 'error')),
    approval_error TEXT,
    approved_at TIMESTAMP,
    approved_by_user_id INTEGER REFERENCES users(user_id) ON DELETE SET NULL,

    import_batch_id UUID,
    imported_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
    created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,

    CONSTRAINT uq_simply_subscription_staging_source UNIQUE (source_system, source_record_id)
);

CREATE INDEX IF NOT EXISTS idx_simply_sub_staging_status
    ON simply_subscription_staging(approval_status);

CREATE INDEX IF NOT EXISTS idx_simply_sub_staging_account
    ON simply_subscription_staging(source_account_id);

CREATE INDEX IF NOT EXISTS idx_simply_sub_staging_hub_customer
    ON simply_subscription_staging(hub_customer_id);

CREATE INDEX IF NOT EXISTS idx_simply_sub_staging_batch
    ON simply_subscription_staging(import_batch_id);

DROP TRIGGER IF EXISTS trigger_simply_subscription_staging_updated_at ON simply_subscription_staging;
CREATE TRIGGER trigger_simply_subscription_staging_updated_at
BEFORE UPDATE ON simply_subscription_staging
FOR EACH ROW
EXECUTE FUNCTION update_updated_at_column();
