/**
 * 백링크 카운트 자동 집계 (Cloud Functions)
 * 
 * 문서 생성/수정/삭제 시 outgoingLinkIds 변경을 감지하여
 * 대상 문서의 incomingLinkCount를 자동으로 ±1 갱신합니다.
 * 
 * 생성일: 2026-02-10 20:47
 */

import * as functions from 'firebase-functions';
import * as admin from 'firebase-admin';

// Firebase Admin 초기화
if (!admin.apps.length) {
    admin.initializeApp();
}

const db = admin.firestore();

/**
 * Firestore onWrite 트리거
 * documents/{docId} 문서가 생성/수정/삭제될 때 실행
 */
export const aggregateBacklinks = functions.firestore
    .document('documents/{docId}')
    .onWrite(async (change, context) => {
        const docId = context.params.docId;

        // 변경 전/후의 outgoingLinkIds 추출
        const beforeData = change.before.exists ? change.before.data() : null;
        const afterData = change.after.exists ? change.after.data() : null;

        const beforeLinks: string[] = beforeData?.outgoingLinkIds || [];
        const afterLinks: string[] = afterData?.outgoingLinkIds || [];

        // 자기 자신에 대한 링크는 제외
        const filteredBefore = beforeLinks.filter(id => id !== docId);
        const filteredAfter = afterLinks.filter(id => id !== docId);

        // 추가된 링크와 제거된 링크 계산
        const added = filteredAfter.filter(id => !filteredBefore.includes(id));
        const removed = filteredBefore.filter(id => !filteredAfter.includes(id));

        // 변경 사항이 없으면 종료
        if (added.length === 0 && removed.length === 0) {
            return null;
        }

        // 배치 업데이트로 일괄 처리
        const batch = db.batch();

        // 추가된 링크 대상: incomingLinkCount +1
        for (const targetId of added) {
            const targetRef = db.collection('documents').doc(targetId);
            batch.update(targetRef, {
                incomingLinkCount: admin.firestore.FieldValue.increment(1)
            });
        }

        // 제거된 링크 대상: incomingLinkCount -1
        for (const targetId of removed) {
            const targetRef = db.collection('documents').doc(targetId);
            batch.update(targetRef, {
                incomingLinkCount: admin.firestore.FieldValue.increment(-1)
            });
        }

        try {
            await batch.commit();
            console.log(
                `[aggregateBacklinks] docId=${docId}: ` +
                `added=${added.length}, removed=${removed.length}`
            );
        } catch (error) {
            // 대상 문서가 존재하지 않는 경우 (유령 문서 등) 무시
            console.warn(
                `[aggregateBacklinks] 일부 대상 문서 업데이트 실패 (유령 문서 가능): `,
                error
            );
        }

        return null;
    });
