-- Ask Ash AI Credits: wallet, ledger, plans, feature pricing, usage logs.
-- Phase 1 of docs/ASK_ASH_BILLING_ARCHITECTURE.md (nxtgauge-ai-assistant repo).
--
-- This is a net-new schema. It does not extend or replace the existing
-- company_ai_usage / job_seeker_ai_usage daily-count quota tables
-- (20260425000000_ai_usage.up.sql) -- those stay in place until a later
-- migration phase consolidates users onto this system (see Section 19 of
-- the architecture doc). It also does not touch tracecoin_wallets /
-- tracecoin_ledger, which remain a completely separate currency.

BEGIN;

CREATE TABLE ai_plans (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    code VARCHAR(50) UNIQUE NOT NULL,
    name VARCHAR(100) NOT NULL,
    monthly_credits INT NOT NULL,
    daily_action_limit INT NOT NULL,
    daily_credit_limit INT,
    allowed_models JSONB NOT NULL DEFAULT '[]',
    allowed_features JSONB NOT NULL DEFAULT '[]',
    is_trial BOOLEAN NOT NULL DEFAULT FALSE,
    trial_days INT,
    is_active BOOLEAN NOT NULL DEFAULT TRUE,
    created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);

-- The AI credits wallet. One row per user, mirroring tracecoin_wallets'
-- balance/reserved shape (crates/db/src/models/tracecoin_wallet.rs) but
-- split into pools (monthly/purchased/bonus) so expiry and consumption
-- order can differ per pool -- see Section 4 of the architecture doc.
CREATE TABLE user_ai_subscriptions (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    user_id UUID UNIQUE NOT NULL REFERENCES users(id) ON DELETE CASCADE,
    plan_id UUID NOT NULL REFERENCES ai_plans(id),
    role_code VARCHAR(50),

    monthly_credits_total INT NOT NULL DEFAULT 0,
    monthly_credits_used INT NOT NULL DEFAULT 0,
    purchased_credits_total INT NOT NULL DEFAULT 0,
    purchased_credits_used INT NOT NULL DEFAULT 0,
    bonus_credits_total INT NOT NULL DEFAULT 0,
    bonus_credits_used INT NOT NULL DEFAULT 0,

    reserved_credits INT NOT NULL DEFAULT 0,
    locked_credits INT NOT NULL DEFAULT 0,

    lifetime_purchased_credits INT NOT NULL DEFAULT 0,
    lifetime_used_credits INT NOT NULL DEFAULT 0,

    daily_actions_used INT NOT NULL DEFAULT 0,
    daily_credits_used INT NOT NULL DEFAULT 0,
    daily_usage_date DATE NOT NULL DEFAULT CURRENT_DATE,

    purchased_credits_expire_at TIMESTAMPTZ,

    billing_cycle VARCHAR(20) NOT NULL DEFAULT 'monthly',
    auto_renew BOOLEAN NOT NULL DEFAULT TRUE,
    current_period_start TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    current_period_end TIMESTAMPTZ NOT NULL DEFAULT (NOW() + INTERVAL '30 days'),
    status VARCHAR(30) NOT NULL DEFAULT 'active',

    created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),

    CONSTRAINT chk_ai_wallet_nonnegative CHECK (
        monthly_credits_used >= 0 AND monthly_credits_used <= monthly_credits_total
        AND purchased_credits_used >= 0 AND purchased_credits_used <= purchased_credits_total
        AND bonus_credits_used >= 0 AND bonus_credits_used <= bonus_credits_total
        AND reserved_credits >= 0
        AND locked_credits >= 0
    )
);

CREATE TABLE ai_feature_costs (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    feature_code VARCHAR(100) UNIQUE NOT NULL,
    display_name VARCHAR(150) NOT NULL,
    default_model VARCHAR(100) NOT NULL,
    credit_cost INT NOT NULL,
    max_input_tokens INT,
    max_output_tokens INT,
    min_plan_code VARCHAR(50),
    priority VARCHAR(20) NOT NULL DEFAULT 'normal',
    timeout_ms INT NOT NULL DEFAULT 15000,
    rate_limit_per_minute INT,
    retry_policy JSONB NOT NULL DEFAULT '{"max_retries": 1, "backoff_ms": 500}',
    fallback_model VARCHAR(100),
    is_active BOOLEAN NOT NULL DEFAULT TRUE,
    created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);

CREATE TABLE ai_usage_logs (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    user_id UUID NOT NULL REFERENCES users(id),
    role_code VARCHAR(50),
    feature_code VARCHAR(100) NOT NULL,
    model_alias VARCHAR(100) NOT NULL,
    credits_charged INT NOT NULL,
    input_tokens INT,
    output_tokens INT,
    total_tokens INT,
    cached_tokens INT,
    provider_reported_cost NUMERIC(12, 6),
    internal_cost NUMERIC(12, 6),
    credit_unit_price_at_time NUMERIC(12, 6),
    status VARCHAR(30) NOT NULL,
    request_id VARCHAR(100),
    error_message TEXT,
    created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);

-- Immutable append-only ledger -- the source of truth for wallet balances
-- (Section 5 of the architecture doc). Application code must never UPDATE
-- or DELETE rows here; corrections are new rows referencing the row they
-- correct via reference_type='ledger_entry'/reference_id.
CREATE TABLE ai_credit_ledger (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    wallet_id UUID NOT NULL REFERENCES user_ai_subscriptions(id),
    entry_type VARCHAR(40) NOT NULL,
    credits INT NOT NULL,
    balance_after INT NOT NULL,
    idempotency_key VARCHAR(150) UNIQUE,
    reference_type VARCHAR(50),
    reference_id UUID,
    actor_type VARCHAR(20) NOT NULL DEFAULT 'user',
    actor_id UUID,
    metadata JSONB,
    created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);

-- Backs the reserve -> capture/release flow (Section 4.2). A background
-- reaper (Phase 1 follow-up, not yet implemented) releases `held` rows
-- past expires_at back to the wallet's available balance.
CREATE TABLE ai_reservation_holds (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    wallet_id UUID NOT NULL REFERENCES user_ai_subscriptions(id),
    credits_held INT NOT NULL,
    feature_code VARCHAR(100) NOT NULL,
    request_id VARCHAR(150),
    idempotency_key VARCHAR(150) UNIQUE,
    status VARCHAR(20) NOT NULL DEFAULT 'held',
    created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    expires_at TIMESTAMPTZ NOT NULL DEFAULT (NOW() + INTERVAL '5 minutes'),
    resolved_at TIMESTAMPTZ
);

CREATE INDEX idx_user_ai_subscriptions_user_id ON user_ai_subscriptions(user_id);
CREATE INDEX idx_user_ai_subscriptions_plan_id ON user_ai_subscriptions(plan_id);
CREATE INDEX idx_ai_usage_logs_user_id ON ai_usage_logs(user_id);
CREATE INDEX idx_ai_usage_logs_feature_code ON ai_usage_logs(feature_code);
CREATE INDEX idx_ai_usage_logs_created_at ON ai_usage_logs(created_at);
CREATE INDEX idx_ai_credit_ledger_wallet_id ON ai_credit_ledger(wallet_id, created_at);
CREATE INDEX idx_ai_credit_ledger_reference ON ai_credit_ledger(reference_type, reference_id);
CREATE INDEX idx_ai_reservation_holds_wallet_id ON ai_reservation_holds(wallet_id);
CREATE INDEX idx_ai_reservation_holds_status_expires ON ai_reservation_holds(status, expires_at) WHERE status = 'held';

-- Seed a minimal Free plan so ensure_wallet() always has a plan to assign
-- new users to. Feature costs / higher tiers are a Phase 3 (packages/
-- plans admin) concern, not seeded here to avoid inventing real prices in
-- a migration -- see Appendix Q4 of the architecture doc.
INSERT INTO ai_plans (code, name, monthly_credits, daily_action_limit, daily_credit_limit, allowed_models, allowed_features)
VALUES ('free', 'Free', 10, 3, 10, '["askash-fast"]', '[]');

COMMIT;
