-- Refund architecture for AI credits (Task 5)
-- Tracks refunds for failed or disputed AI credit charges

BEGIN;

CREATE TABLE ai_refunds (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
    ledger_debit_entry_id UUID NOT NULL REFERENCES ai_credit_ledger(id),
    credits_refunded INT NOT NULL CHECK (credits_refunded > 0),
    reason VARCHAR(50) NOT NULL CHECK (reason IN ('provider_failure', 'timeout', 'validation_failure', 'manual', 'user_dispute')),
    initiated_by VARCHAR(20) NOT NULL CHECK (initiated_by IN ('system', 'admin', 'user_dispute')),
    status VARCHAR(20) NOT NULL DEFAULT 'pending' CHECK (status IN ('pending', 'approved', 'rejected', 'completed')),
    notes TEXT,
    admin_actor_id UUID REFERENCES users(id),
    idempotency_key VARCHAR(150) UNIQUE,
    created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    resolved_at TIMESTAMPTZ,
    updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);

-- Indexes for common queries
CREATE INDEX idx_ai_refunds_user_id ON ai_refunds(user_id);
CREATE INDEX idx_ai_refunds_status ON ai_refunds(status);
CREATE INDEX idx_ai_refunds_ledger_entry ON ai_refunds(ledger_debit_entry_id);
CREATE INDEX idx_ai_refunds_created_at ON ai_refunds(created_at DESC);

-- Add entry_type for refunds to ai_credit_ledger (if not exists)
-- The existing entry_type column should support 'refund' values
-- No schema change needed - just ensure application uses 'refund' entry_type

COMMIT;
