-- Migration: 008_add_co_managed_wallet_fields
-- Description: Add wallet_name and invite_code fields for co-managed wallet sessions
--              and extend session_type to support 'co_managed_keygen'
-- This migration is idempotent - safe to run multiple times

-- Add new columns for co-managed wallet sessions (idempotent)
DO $$
BEGIN
    IF NOT EXISTS (SELECT 1 FROM information_schema.columns
                   WHERE table_name = 'mpc_sessions' AND column_name = 'wallet_name') THEN
        ALTER TABLE mpc_sessions ADD COLUMN wallet_name VARCHAR(255);
    END IF;

    IF NOT EXISTS (SELECT 1 FROM information_schema.columns
                   WHERE table_name = 'mpc_sessions' AND column_name = 'invite_code') THEN
        ALTER TABLE mpc_sessions ADD COLUMN invite_code VARCHAR(50);
    END IF;
END $$;

-- Create index for invite_code lookups (idempotent)
CREATE INDEX IF NOT EXISTS idx_mpc_sessions_invite_code ON mpc_sessions(invite_code) WHERE invite_code IS NOT NULL;

-- Drop the existing session_type constraint
ALTER TABLE mpc_sessions DROP CONSTRAINT IF EXISTS chk_session_type;

-- Add updated session_type constraint including 'co_managed_keygen'
ALTER TABLE mpc_sessions
    ADD CONSTRAINT chk_session_type CHECK (session_type IN ('keygen', 'sign', 'co_managed_keygen'));

-- Add comment for the new columns (safe to run multiple times)
COMMENT ON COLUMN mpc_sessions.wallet_name IS 'Wallet name for co-managed wallet sessions';
COMMENT ON COLUMN mpc_sessions.invite_code IS 'Invite code for co-managed wallet sessions - used for participants to join';
