-- 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.
--
-- REWRITTEN 2026-08-13: this migration was originally CREATE TABLE for all
-- six tables below, but got disabled (renamed .up.sql.skip) in commit
-- 0163349 because ai_plans/user_ai_subscriptions/ai_feature_costs/
-- ai_usage_logs already existed in prod from an earlier, narrower schema
-- pass -- the batch "relation already exists" error aborted the whole
-- script on table 1, silently leaving ai_credit_ledger and
-- ai_reservation_holds (which crates/db/src/models/ai_credits.rs's
-- try_reserve_credits/settle/release actually depend on) never created at
-- all, despite the wallet system being actively wired into
-- apps/users/src/handlers/ai_credits.rs, apps/payments, apps/cron and
-- already holding real subscription rows. Rewritten to be idempotent:
-- ADD COLUMN IF NOT EXISTS to bring the 4 pre-existing tables up to the
-- full column set the application code expects (safe defaults, no data
-- loss), and CREATE TABLE IF NOT EXISTS for the 2 genuinely-missing ones.

BEGIN;

-- ── ai_plans: add columns introduced after the table's original creation ──
ALTER TABLE ai_plans ADD COLUMN IF NOT EXISTS daily_credit_limit INT;
ALTER TABLE ai_plans ADD COLUMN IF NOT EXISTS is_trial BOOLEAN NOT NULL DEFAULT FALSE;
ALTER TABLE ai_plans ADD COLUMN IF NOT EXISTS trial_days INT;

-- ── user_ai_subscriptions: bring up to the wallet shape the code expects ──
-- (crates/db/src/models/ai_credits.rs's AiSubscriptionWallet struct).
-- Existing rows backfill lifetime_*/bonus_*/reserved/locked to 0 -- these
-- are new cumulative counters with no prior history to reconstruct, not a
-- correction of existing monthly_credits_used/purchased_credits_used
-- (which are untouched and remain authoritative for what they track).
ALTER TABLE user_ai_subscriptions ADD COLUMN IF NOT EXISTS bonus_credits_total INT NOT NULL DEFAULT 0;
ALTER TABLE user_ai_subscriptions ADD COLUMN IF NOT EXISTS bonus_credits_used INT NOT NULL DEFAULT 0;
ALTER TABLE user_ai_subscriptions ADD COLUMN IF NOT EXISTS reserved_credits INT NOT NULL DEFAULT 0;
ALTER TABLE user_ai_subscriptions ADD COLUMN IF NOT EXISTS locked_credits INT NOT NULL DEFAULT 0;
ALTER TABLE user_ai_subscriptions ADD COLUMN IF NOT EXISTS lifetime_purchased_credits INT NOT NULL DEFAULT 0;
ALTER TABLE user_ai_subscriptions ADD COLUMN IF NOT EXISTS lifetime_used_credits INT NOT NULL DEFAULT 0;
ALTER TABLE user_ai_subscriptions ADD COLUMN IF NOT EXISTS daily_credits_used INT NOT NULL DEFAULT 0;
ALTER TABLE user_ai_subscriptions ADD COLUMN IF NOT EXISTS daily_usage_date DATE NOT NULL DEFAULT CURRENT_DATE;
ALTER TABLE user_ai_subscriptions ADD COLUMN IF NOT EXISTS purchased_credits_expire_at TIMESTAMPTZ;
ALTER TABLE user_ai_subscriptions ADD COLUMN IF NOT EXISTS billing_cycle VARCHAR(20) NOT NULL DEFAULT 'monthly';
ALTER TABLE user_ai_subscriptions ADD COLUMN IF NOT EXISTS auto_renew BOOLEAN NOT NULL DEFAULT TRUE;

-- Matches the original migration's chk_ai_wallet_nonnegative, guarded since
-- Postgres has no ADD CONSTRAINT IF NOT EXISTS. Safe against the 3 existing
-- rows: all newly-added columns default to 0, which trivially satisfies >= 0.
DO $$
BEGIN
    IF NOT EXISTS (
        SELECT 1 FROM pg_constraint WHERE conname = 'chk_ai_wallet_nonnegative_v2'
    ) THEN
        ALTER TABLE user_ai_subscriptions ADD CONSTRAINT chk_ai_wallet_nonnegative_v2 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
        );
    END IF;
END $$;

-- ── ai_feature_costs: columns the pricing/dispatch code reads ─────────────
-- (crates/db/src/models/ai_credits.rs's feature-cost SELECT lists
-- min_plan_code, timeout_ms, fallback_model explicitly -- these were
-- erroring with "column does not exist" against the live table before
-- this migration).
ALTER TABLE ai_feature_costs ADD COLUMN IF NOT EXISTS min_plan_code VARCHAR(50);
ALTER TABLE ai_feature_costs ADD COLUMN IF NOT EXISTS priority VARCHAR(20) NOT NULL DEFAULT 'normal';
ALTER TABLE ai_feature_costs ADD COLUMN IF NOT EXISTS timeout_ms INT NOT NULL DEFAULT 15000;
ALTER TABLE ai_feature_costs ADD COLUMN IF NOT EXISTS rate_limit_per_minute INT;
ALTER TABLE ai_feature_costs ADD COLUMN IF NOT EXISTS retry_policy JSONB NOT NULL DEFAULT '{"max_retries": 1, "backoff_ms": 500}';
ALTER TABLE ai_feature_costs ADD COLUMN IF NOT EXISTS fallback_model VARCHAR(100);

-- ── ai_usage_logs: cost-tracking columns from the original design ─────────
-- (prompt_preview/response_preview already exist in prod from a later,
-- separate migration not part of this file -- left untouched).
ALTER TABLE ai_usage_logs ADD COLUMN IF NOT EXISTS cached_tokens INT;
ALTER TABLE ai_usage_logs ADD COLUMN IF NOT EXISTS provider_reported_cost NUMERIC(12, 6);
ALTER TABLE ai_usage_logs ADD COLUMN IF NOT EXISTS internal_cost NUMERIC(12, 6);
ALTER TABLE ai_usage_logs ADD COLUMN IF NOT EXISTS credit_unit_price_at_time NUMERIC(12, 6);

-- ── Genuinely missing tables ───────────────────────────────────────────────

-- 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 IF NOT EXISTS 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 (crates/db/tests/ai_credits_reaper.rs / apps/cron) releases `held`
-- rows past expires_at back to the wallet's available balance.
CREATE TABLE IF NOT EXISTS 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 IF NOT EXISTS idx_ai_credit_ledger_wallet_id ON ai_credit_ledger(wallet_id, created_at);
CREATE INDEX IF NOT EXISTS idx_ai_credit_ledger_reference ON ai_credit_ledger(reference_type, reference_id);
CREATE INDEX IF NOT EXISTS idx_ai_reservation_holds_wallet_id ON ai_reservation_holds(wallet_id);
CREATE INDEX IF NOT EXISTS idx_ai_reservation_holds_status_expires ON ai_reservation_holds(status, expires_at) WHERE status = 'held';

-- Free plan already exists in prod (seeded some other way) -- don't fail on it.
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"]', '[]')
ON CONFLICT (code) DO NOTHING;

COMMIT;
