
import { NextRequest, NextResponse } from 'next/server';
import { getFirebaseAdmin } from '@/lib/firebase-admin';
import { getAuth } from 'firebase-admin/auth';
import { ADMIN_EMAILS } from '@/lib/constants';

export async function DELETE(req: NextRequest) {
    try {
        // 1. Authentication Check
        const authHeader = req.headers.get('Authorization');
        if (!authHeader?.startsWith('Bearer ')) {
            return NextResponse.json({ error: 'Unauthorized: Missing token' }, { status: 401 });
        }
        const idToken = authHeader.split('Bearer ')[1];

        let decodedToken;
        try {
            decodedToken = await getAuth().verifyIdToken(idToken);
        } catch (error) {
            console.error('Token verification failed:', error);
            return NextResponse.json({ error: 'Unauthorized: Invalid token' }, { status: 401 });
        }

        // 2. Get Document ID & Fetch Document
        const { searchParams } = new URL(req.url);
        const docId = searchParams.get('docId');

        if (!docId) {
            return NextResponse.json({ error: 'Bad Request: docId is required' }, { status: 400 });
        }

        const adminDb = getFirebaseAdmin().firestore();
        const docRef = adminDb.collection('documents').doc(docId);
        const docSnap = await docRef.get();

        if (!docSnap.exists) {
            return NextResponse.json({ error: 'Document not found' }, { status: 404 });
        }

        const docData = docSnap.data();

        // 3. Permission Check (Admin OR Author)
        const userEmail = decodedToken.email;
        const userUid = decodedToken.uid;
        const isAdmin = userEmail && ADMIN_EMAILS.includes(userEmail);
        const isAuthor = docData?.authorId === userUid;

        // [Fix] Allow deleting Daily Notes if the ID contains the user's UID (e.g. daily-2026-02-19-UID)
        // This is a safety fallback if authorId is missing or mismatching
        const isDailyOwner = docId.startsWith('daily-') && docId.includes(userUid);

        // 작성자 본인 확인
        const hasAuthorOwnership = isAuthor || isDailyOwner;

        if (!isAdmin) {
            if (!hasAuthorOwnership) {
                console.warn(`Unauthorized purge attempt by: ${userEmail} (uid: ${userUid}) on doc ${docId}`);
                return NextResponse.json({ error: 'Forbidden: You can only delete your own documents' }, { status: 403 });
            }

            // [Policy Update] 일반 사용자는 'private' 문서(My, Daily)만 영구삭제 가능.
            // 위키 등 퍼블릭 문서는 작성자 본인이라도 영구삭제 불가 (관리자에게만 허용)
            // (docType이 'daily'이거나, visibility가 'private'인 경우만 허용)
            const isPrivateDoc = docData?.visibility === 'private' || docData?.docType === 'daily' || docId.startsWith('daily-');
            if (!isPrivateDoc) {
                console.warn(`Attempt to purge public wiki by non-admin author: ${userEmail} on doc ${docId}`);
                return NextResponse.json({ error: 'Forbidden: 공개된 위키 문서는 관리자만 영구 삭제할 수 있습니다. 관리자에게 요청해주세요.' }, { status: 403 });
            }
        }

        // 4. Verification: Check if doc is soft-deleted
        // Ensure it is soft-deleted before purging (Double safety)
        if (docData?.isDeleted !== true) {
            return NextResponse.json({ error: 'Document must be soft-deleted before purging' }, { status: 400 });
        }

        // 5. Recursive Delete (Document + Subcollections like 'revisions')
        // firestore.recursiveDelete is available in firebase-admin v11+
        await adminDb.recursiveDelete(docRef);

        return NextResponse.json({ success: true, message: `Document ${docId} permanently deleted` });

    } catch (error: any) {
        console.error('Purge API Error:', error);
        return NextResponse.json({
            error: 'Internal Server Error',
            details: error.message
        }, { status: 500 });
    }
}
