import { NextRequest, NextResponse } from 'next/server';
import { adminDb } from '@/lib/firebase-admin';
import { verifyMember } from '@/lib/auth-middleware';
import type { InsuranceMetadata } from '@/types/firestore';

/**
 * CL-7: 과거 약관 버전 조회 — 버전 목록 API
 *
 * GET /api/ai/versions?productId=xxx
 *
 * 흐름:
 * 1. Firebase Auth 검증
 * 2. productId 필수 파라미터 확인
 * 3. insurance_metadata 컬렉션에서 해당 productId의 모든 버전 조회
 * 4. effectiveDate 내림차순 정렬 후 현행/과거 구분 표시
 */

export async function GET(req: NextRequest): Promise<NextResponse> {
    try {
        // ── Firebase ID Token 검증 ─────────────────────────────────────
        const authResult = await verifyMember(req);
        if (authResult instanceof NextResponse) return authResult;

        // ── 파라미터 파싱 ──────────────────────────────────────────────
        const { searchParams } = new URL(req.url);
        const productId = searchParams.get('productId');

        if (!productId || productId.trim().length === 0) {
            return NextResponse.json(
                { error: 'productId는 필수 파라미터입니다.' },
                { status: 400 }
            );
        }

        const db = adminDb;

        // ── insurance_metadata에서 해당 productId의 전체 버전 조회 ─────
        const metaSnap = await db.collection('insurance_metadata')
            .where('productId', '==', productId.trim())
            .where('isActive', '==', true)
            .get();

        if (metaSnap.empty) {
            return NextResponse.json(
                { error: '해당 productId의 등록된 약관을 찾을 수 없습니다.' },
                { status: 404 }
            );
        }

        const allMetadata: InsuranceMetadata[] = metaSnap.docs.map(
            (doc: FirebaseFirestore.QueryDocumentSnapshot) => ({ id: doc.id, ...doc.data() } as InsuranceMetadata)
        );

        // ── productName, companyName은 첫 번째 문서에서 추출 (비정규화 필드) ──
        // 가장 최신 버전(end가 없는 현행)을 우선으로 대표값 사용
        const currentDoc = allMetadata.find((m: InsuranceMetadata) => !m.effectiveDateRange?.end) ?? allMetadata[0];
        const productName = currentDoc.productName;
        const companyName = currentDoc.companyName;

        // ── 버전 목록 구성 ──────────────────────────────────────────────
        const versions = allMetadata
            .filter((m: InsuranceMetadata) => m.effectiveDateRange?.start)
            .map((m: InsuranceMetadata) => {
                const isCurrent = !m.effectiveDateRange?.end;
                return {
                    effectiveDate: m.effectiveDateRange!.start,
                    endDate: m.effectiveDateRange?.end ?? null,
                    isCurrent,
                };
            })
            // effectiveDate 내림차순 정렬 (최신이 먼저, YYYY-MM 사전식 비교)
            .sort((a: { effectiveDate: string }, b: { effectiveDate: string }) => b.effectiveDate.localeCompare(a.effectiveDate));

        return NextResponse.json({
            versions,
            productName,
            companyName,
        });

    } catch (error: any) {
        console.error('Versions API Error:', error);
        return NextResponse.json({ error: error.message }, { status: 500 });
    }
}
