BEGIN;

DROP INDEX IF EXISTS idx_ai_reservation_holds_status_expires;
DROP INDEX IF EXISTS idx_ai_reservation_holds_wallet_id;
DROP INDEX IF EXISTS idx_ai_credit_ledger_reference;
DROP INDEX IF EXISTS idx_ai_credit_ledger_wallet_id;

DROP TABLE IF EXISTS ai_reservation_holds;
DROP TABLE IF EXISTS ai_credit_ledger;

-- NOTE: ai_plans, user_ai_subscriptions, ai_feature_costs, and ai_usage_logs
-- are NOT dropped here (unlike the original version of this file) -- they
-- predate this migration (created by an earlier, separate schema pass) and
-- hold real production subscription data. This down-migration only reverses
-- what the corresponding up.sql actually added: the 2 new tables/indexes and
-- the columns/constraint below.

ALTER TABLE user_ai_subscriptions DROP CONSTRAINT IF EXISTS chk_ai_wallet_nonnegative_v2;

ALTER TABLE ai_plans DROP COLUMN IF EXISTS daily_credit_limit;
ALTER TABLE ai_plans DROP COLUMN IF EXISTS is_trial;
ALTER TABLE ai_plans DROP COLUMN IF EXISTS trial_days;

ALTER TABLE user_ai_subscriptions DROP COLUMN IF EXISTS bonus_credits_total;
ALTER TABLE user_ai_subscriptions DROP COLUMN IF EXISTS bonus_credits_used;
ALTER TABLE user_ai_subscriptions DROP COLUMN IF EXISTS reserved_credits;
ALTER TABLE user_ai_subscriptions DROP COLUMN IF EXISTS locked_credits;
ALTER TABLE user_ai_subscriptions DROP COLUMN IF EXISTS lifetime_purchased_credits;
ALTER TABLE user_ai_subscriptions DROP COLUMN IF EXISTS lifetime_used_credits;
ALTER TABLE user_ai_subscriptions DROP COLUMN IF EXISTS daily_credits_used;
ALTER TABLE user_ai_subscriptions DROP COLUMN IF EXISTS daily_usage_date;
ALTER TABLE user_ai_subscriptions DROP COLUMN IF EXISTS purchased_credits_expire_at;
ALTER TABLE user_ai_subscriptions DROP COLUMN IF EXISTS billing_cycle;
ALTER TABLE user_ai_subscriptions DROP COLUMN IF EXISTS auto_renew;

ALTER TABLE ai_feature_costs DROP COLUMN IF EXISTS min_plan_code;
ALTER TABLE ai_feature_costs DROP COLUMN IF EXISTS priority;
ALTER TABLE ai_feature_costs DROP COLUMN IF EXISTS timeout_ms;
ALTER TABLE ai_feature_costs DROP COLUMN IF EXISTS rate_limit_per_minute;
ALTER TABLE ai_feature_costs DROP COLUMN IF EXISTS retry_policy;
ALTER TABLE ai_feature_costs DROP COLUMN IF EXISTS fallback_model;

ALTER TABLE ai_usage_logs DROP COLUMN IF EXISTS cached_tokens;
ALTER TABLE ai_usage_logs DROP COLUMN IF EXISTS provider_reported_cost;
ALTER TABLE ai_usage_logs DROP COLUMN IF EXISTS internal_cost;
ALTER TABLE ai_usage_logs DROP COLUMN IF EXISTS credit_unit_price_at_time;

COMMIT;
