/**
 * 만료된 문서 잠금 자동 정리 (Cloud Functions)
 * 
 * 설계 문서: docs/decisions/260208-21.12-concurrent-editing.md
 * 생성일: 2026-02-08 21:14
 * 
 * 실행 주기: 매 10분
 */

import * as functions from 'firebase-functions';
import * as admin from 'firebase-admin';

// Firebase Admin 초기화
if (!admin.apps.length) {
    admin.initializeApp();
}

const db = admin.firestore();

// ============================================
// 상수
// ============================================

const LOCK_TIMEOUT_MS = 30 * 60 * 1000; // 30분

// ============================================
// 만료 잠금 정리 스케줄러
// ============================================

export const cleanupExpiredLocks = functions.pubsub
    .schedule('every 10 minutes')
    .onRun(async (context) => {
        const thirtyMinutesAgo = admin.firestore.Timestamp.fromDate(
            new Date(Date.now() - LOCK_TIMEOUT_MS)
        );

        try {
            // 만료된 잠금이 있는 문서 조회
            const expiredDocs = await db.collection('documents')
                .where('editingBy', '!=', null)
                .where('editingAt', '<', thirtyMinutesAgo)
                .get();

            if (expiredDocs.empty) {
                console.log('No expired locks found');
                return null;
            }

            // 배치로 잠금 해제
            const batch = db.batch();

            expiredDocs.forEach((doc) => {
                const data = doc.data();
                console.log(`Releasing expired lock: docId=${doc.id}, user=${data.editingByName}`);

                batch.update(doc.ref, {
                    editingBy: null,
                    editingByName: null,
                    editingAt: null
                });
            });

            await batch.commit();
            console.log(`Cleaned up ${expiredDocs.size} expired locks`);

            return null;
        } catch (error) {
            console.error('Error cleaning up expired locks:', error);
            throw error;
        }
    });

// ============================================
// 페이지 떠날 때 잠금 해제 (HTTP Trigger - 선택)
// ============================================

export const releaseDocumentLock = functions.https.onCall(
    async (data, context) => {
        // 인증 확인
        if (!context.auth) {
            throw new functions.https.HttpsError(
                'unauthenticated',
                'User must be authenticated'
            );
        }

        const { docId } = data;
        const userId = context.auth.uid;

        if (!docId) {
            throw new functions.https.HttpsError(
                'invalid-argument',
                'Document ID is required'
            );
        }

        const docRef = db.collection('documents').doc(docId);

        try {
            await db.runTransaction(async (transaction) => {
                const doc = await transaction.get(docRef);

                if (!doc.exists) {
                    return;
                }

                // 본인 잠금만 해제
                if (doc.data()?.editingBy === userId) {
                    transaction.update(docRef, {
                        editingBy: null,
                        editingByName: null,
                        editingAt: null
                    });
                }
            });

            return { success: true };
        } catch (error) {
            console.error('Error releasing lock:', error);
            throw new functions.https.HttpsError('internal', 'Failed to release lock');
        }
    }
);
