-- =============================================================
-- V024: Deprecate legacy Telegram-specific columns
-- =============================================================
-- Scope: Complete platform migration by backfilling any remaining
-- external_* gaps and officially deprecating telegram_* columns.
-- No columns are dropped — rollback-safe.
-- =============================================================

-- 1. Backfill players platform identity (safeguard for any rows missed in V016)
UPDATE players
   SET platform          = 'Telegram',
       external_user_id  = telegram_id::TEXT,
       external_username = telegram_username
 WHERE platform IS NULL;

-- 2. Backfill game_groups platform identity (safeguard for any rows missed in V016)
UPDATE game_groups
   SET platform          = 'Telegram',
       external_group_id = telegram_chat_id::TEXT
 WHERE platform IS NULL;

-- 3. Add platform identity to calendar_subscriptions
ALTER TABLE calendar_subscriptions
    ADD COLUMN user_platform   VARCHAR(50),
    ADD COLUMN user_external_id VARCHAR(255);

UPDATE calendar_subscriptions
   SET user_external_id = user_telegram_id::TEXT,
       user_platform    = 'Telegram'
 WHERE user_platform IS NULL;

-- 4. Migrate calendar subscription index
DROP INDEX IF EXISTS ix_calendar_subscriptions_user_telegram_id;
CREATE INDEX ix_calendar_subscriptions_user_external_id ON calendar_subscriptions (user_external_id);

-- 5. Deprecation comments on legacy columns
COMMENT ON COLUMN players.telegram_id         IS 'DEPRECATED: use platform + external_user_id';
COMMENT ON COLUMN players.telegram_username   IS 'DEPRECATED: use external_username';
COMMENT ON COLUMN game_groups.telegram_chat_id IS 'DEPRECATED: use platform + external_group_id';
COMMENT ON COLUMN game_groups.gm_telegram_id   IS 'DEPRECATED: group ownership is tracked in group_managers';
COMMENT ON COLUMN calendar_subscriptions.user_telegram_id IS 'DEPRECATED: use user_platform + user_external_id';
