/**
 * Task I: youtube_channels 초기 시딩 스크립트
 *
 * 실행: (functions/ 디렉토리에서)
 *   npx ts-node -e "require('./src/seedYoutubeChannels')"
 *   또는
 *   node -e "require('./lib/seedYoutubeChannels')" (빌드 후)
 */

import * as admin from 'firebase-admin';
import { google } from 'googleapis';

if (!admin.apps.length) {
    admin.initializeApp(); // Cloud 환경 또는 GOOGLE_APPLICATION_CREDENTIALS 사용
}
const db = admin.firestore();

const CHANNELS_TO_REGISTER = [
    { handle: '보험명의정닥터', channelName: '보험명의정닥터', includeShorts: true },
    { handle: 'ins-king',       channelName: '인스킹 ins-king', includeShorts: true },
];

async function resolveChannelId(
    youtube: ReturnType<typeof google.youtube>,
    handle: string
): Promise<string | null> {
    const res = await youtube.channels.list({
        part: ['id', 'snippet'],
        forHandle: handle,
    } as any);
    const item = res.data.items?.[0];
    if (!item?.id) {
        console.warn(`⚠️ 핸들 "${handle}" → Channel ID 없음`);
        return null;
    }
    console.log(`✅ @${handle} → ${item.id} (${item.snippet?.title})`);
    return item.id;
}

async function main() {
    const youtubeApiKey = process.env.YOUTUBE_API_KEY;
    if (!youtubeApiKey) {
        console.error('❌ YOUTUBE_API_KEY 없음');
        process.exit(1);
    }
    const youtube = google.youtube({ version: 'v3', auth: youtubeApiKey });
    console.log('🚀 유튜브 채널 시딩 시작...\n');

    for (const ch of CHANNELS_TO_REGISTER) {
        const channelId = await resolveChannelId(youtube, ch.handle);
        if (!channelId) continue;
        const docId = `ch_${ch.handle.replace(/[^a-zA-Z0-9가-힣]/g, '_')}`;
        await db.collection('youtube_channels').doc(docId).set({
            channelId,
            channelName: ch.channelName,
            handle: ch.handle,
            includeShorts: ch.includeShorts,
            isActive: true,
            lastCrawledAt: admin.firestore.Timestamp.fromDate(
                new Date(Date.now() - 7 * 24 * 60 * 60 * 1000)
            ),
            createdAt: admin.firestore.FieldValue.serverTimestamp(),
        }, { merge: true });
        console.log(`📺 등록: ${ch.channelName} (${channelId})`);
    }
    console.log('\n✅ 완료!');
    process.exit(0);
}

main().catch(err => { console.error(err); process.exit(1); });
