-- Subscription lifecycle management (Task 7)
-- Tracks plan changes, proration, and scheduled downgrades

BEGIN;

CREATE TABLE ai_subscription_history (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
    from_plan_id UUID REFERENCES ai_plans(id),
    to_plan_id UUID NOT NULL REFERENCES ai_plans(id),
    change_type VARCHAR(20) NOT NULL CHECK (change_type IN ('upgrade', 'downgrade', 'cancel', 'renew', 'trial_expired')),
    
    -- Proration details (for upgrades)
    proration_credits INT DEFAULT 0, -- Bonus credits granted for mid-period upgrade
    proration_days_remaining INT, -- Days remaining in current period
    
    -- Timing
    effective_at TIMESTAMPTZ NOT NULL,
    created_by UUID REFERENCES users(id), -- System if automated
    
    -- Status
    status VARCHAR(20) NOT NULL DEFAULT 'completed' CHECK (status IN ('scheduled', 'completed', 'cancelled')),
    
    created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);

-- Add columns to user_ai_subscriptions for trial support (if not exists)
-- These are already in the schema from the initial migration
-- - is_trial BOOLEAN
-- - trial_days INT
-- - trial_ends_at TIMESTAMPTZ (needs to be added)

-- Add trial tracking columns if they don't exist
DO $$
BEGIN
    IF NOT EXISTS (SELECT 1 FROM information_schema.columns 
                   WHERE table_name = 'user_ai_subscriptions' 
                   AND column_name = 'is_trial') THEN
        ALTER TABLE user_ai_subscriptions ADD COLUMN is_trial BOOLEAN NOT NULL DEFAULT FALSE;
    END IF;
    
    IF NOT EXISTS (SELECT 1 FROM information_schema.columns 
                   WHERE table_name = 'user_ai_subscriptions' 
                   AND column_name = 'trial_days') THEN
        ALTER TABLE user_ai_subscriptions ADD COLUMN trial_days INT;
    END IF;
    
    IF NOT EXISTS (SELECT 1 FROM information_schema.columns 
                   WHERE table_name = 'user_ai_subscriptions' 
                   AND column_name = 'trial_ends_at') THEN
        ALTER TABLE user_ai_subscriptions ADD COLUMN trial_ends_at TIMESTAMPTZ;
    END IF;
    
    IF NOT EXISTS (SELECT 1 FROM information_schema.columns 
                   WHERE table_name = 'user_ai_subscriptions' 
                   AND column_name = 'downgrade_scheduled_to') THEN
        ALTER TABLE user_ai_subscriptions ADD COLUMN downgrade_scheduled_to UUID REFERENCES ai_plans(id);
 END IF;
END $$;

-- Indexes for subscription management
CREATE INDEX idx_ai_subscription_history_user ON ai_subscription_history(user_id);
CREATE INDEX idx_ai_subscription_history_effective ON ai_subscription_history(effective_at DESC);
CREATE INDEX idx_user_ai_subscriptions_trial ON user_ai_subscriptions(user_id) WHERE is_trial = TRUE;

COMMIT;
