/**
 * Firestore 정기 백업 (Cloud Functions v1)
 * 
 * 설계 문서: docs/specs/260215-21.30-db-backup-spec.md
 * 생성일: 2026-02-15 22:30
 * 
 * 실행 주기: 매일 오전 04:00 (KST)
 * 요구사항: Blaze 요금제, App Engine 활성화, IAM 권한 (Datastore Import/Export Admin)
 */

import * as functions from 'firebase-functions';
import * as firestore from '@google-cloud/firestore';

const client = new firestore.v1.FirestoreAdminClient();

// 백업할 버킷 이름 (환경 변수로 설정하거나 하드코딩)
// 1순위: functions.config().backup.bucket
// 2순위: process.env.BACKUP_BUCKET_NAME
// 3순위: 기본값 (프로젝트 ID 기반)
const BUCKET_NAME = process.env.BACKUP_BUCKET_NAME || 'gs://insuwiki-backups';

export const scheduledFirestoreExport = functions.pubsub
    .schedule('every 24 hours')
    .timeZone('Asia/Seoul')
    .onRun(async (context) => {
        const projectId = process.env.GCP_PROJECT || process.env.GCLOUD_PROJECT;
        const databaseName = client.databasePath(projectId!, '(default)');

        console.log(`Starting Firestore export for project: ${projectId}`);
        console.log(`Target Bucket: ${BUCKET_NAME}`);

        try {
            const [response] = await client.exportDocuments({
                name: databaseName,
                outputUriPrefix: BUCKET_NAME,
                // collectionIds: [] // 빈 배열이면 모든 컬렉션 백업
            });

            console.log(`Export operation started: ${response.name}`);
            return response;
        } catch (error) {
            console.error('Error extracting document:', error);
            throw new Error('Export operation failed');
        }
    });
