-- Migration to cleanup refresh_tokens table
-- Remove legacy column 'token' which caused NULL constraint violations
-- Ensure correct constraints on token_hash
-- This migration runs AFTER 010_auth_and_users.sql which creates the refresh_tokens table

-- Check if the table exists before attempting to alter it
DO $$
BEGIN
    -- Only proceed if the refresh_tokens table exists
    IF EXISTS (
        SELECT 1 FROM information_schema.tables 
        WHERE table_schema = 'public' 
        AND table_name = 'refresh_tokens'
    ) THEN
        -- 1. Remove the legacy 'token' column which is no longer used by the application
        -- The application now uses 'token_hash' for secure storage
        ALTER TABLE refresh_tokens DROP COLUMN IF EXISTS token;

        -- 2. Ensure token_hash has the correct constraints
        -- It should be NOT NULL and UNIQUE to prevent duplicates and ensure integrity
        -- Only set NOT NULL if the column exists and doesn't already have the constraint
        IF EXISTS (
            SELECT 1 FROM information_schema.columns 
            WHERE table_schema = 'public' 
            AND table_name = 'refresh_tokens' 
            AND column_name = 'token_hash'
        ) THEN
            -- Check if column is already NOT NULL
            IF EXISTS (
                SELECT 1 FROM information_schema.columns 
                WHERE table_schema = 'public' 
                AND table_name = 'refresh_tokens' 
                AND column_name = 'token_hash'
                AND is_nullable = 'YES'
            ) THEN
                ALTER TABLE refresh_tokens ALTER COLUMN token_hash SET NOT NULL;
            END IF;
        END IF;

        -- 3. Add comment to clarify the column usage
        COMMENT ON COLUMN refresh_tokens.token_hash IS 'SHA-256 hash of the refresh token. The raw token is never stored.';
    ELSE
        RAISE NOTICE 'Table refresh_tokens does not exist yet. Skipping cleanup migration.';
    END IF;
END $$;
