import { NextRequest, NextResponse } from 'next/server';
import { getFirebaseAdmin } from '@/lib/firebase-admin';
import { getFirestore } from 'firebase-admin/firestore';

const VALID_SOURCES = ['insuro_newsletter', 'insuro_premium'] as const;
type ValidSource = typeof VALID_SOURCES[number];

const MONTH_KEY_REGEX = /^\d{4}-\d{2}$/;

export async function POST(req: NextRequest) {
    // 1. API Key Authentication
    const apiKey = req.headers.get('x-api-key');
    const expectedApiKey = process.env.INSURO_SYNC_API_KEY;

    if (!expectedApiKey || apiKey !== expectedApiKey) {
        return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
    }

    // 2. Parse & Validate Request Body
    let body: Record<string, unknown>;
    try {
        body = await req.json();
    } catch {
        return NextResponse.json({ error: 'Invalid JSON body' }, { status: 400 });
    }

    const { company_name, month_key, title, extracted_text, source, source_id } = body;

    if (!company_name || typeof company_name !== 'string') {
        return NextResponse.json({ error: 'company_name is required and must be a string' }, { status: 400 });
    }
    if (!month_key || typeof month_key !== 'string' || !MONTH_KEY_REGEX.test(month_key)) {
        return NextResponse.json({ error: 'month_key is required and must be in YYYY-MM format' }, { status: 400 });
    }
    if (!title || typeof title !== 'string') {
        return NextResponse.json({ error: 'title is required and must be a string' }, { status: 400 });
    }
    if (!extracted_text || typeof extracted_text !== 'string') {
        return NextResponse.json({ error: 'extracted_text is required and must be a string' }, { status: 400 });
    }
    if (extracted_text.length > 10000) {
        return NextResponse.json({ error: 'extracted_text must be at most 10000 characters' }, { status: 400 });
    }
    if (!source || !VALID_SOURCES.includes(source as ValidSource)) {
        return NextResponse.json({ error: 'source must be one of: insuro_newsletter, insuro_premium' }, { status: 400 });
    }
    if (!source_id || typeof source_id !== 'string') {
        return NextResponse.json({ error: 'source_id is required and must be a string' }, { status: 400 });
    }

    // 3. Save to Firestore
    try {
        const app = getFirebaseAdmin();
        const db = getFirestore(app);

        const docId = `${source}:${source_id}`;
        const docRef = db.collection('newsletter_updates').doc(docId);

        await docRef.set({
            company_name,
            month_key,
            title,
            extracted_text,
            source,
            source_id: source_id as string,
            synced_at: new Date(),
        });

        return NextResponse.json({ status: 'ok', id: docId }, { status: 200 });
    } catch (error) {
        console.error('Firestore write failed:', error);
        return NextResponse.json({ error: 'Internal server error' }, { status: 500 });
    }
}

export async function DELETE(req: NextRequest) {
    // 1. API Key Authentication
    const apiKey = req.headers.get('x-api-key');
    const expectedApiKey = process.env.INSURO_SYNC_API_KEY;

    if (!expectedApiKey || apiKey !== expectedApiKey) {
        return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
    }

    // 2. Parse & Validate Request Body
    let body: Record<string, unknown>;
    try {
        body = await req.json();
    } catch {
        return NextResponse.json({ error: 'Invalid JSON body' }, { status: 400 });
    }

    const { source_id } = body;

    if (!source_id || typeof source_id !== 'string') {
        return NextResponse.json({ error: 'source_id is required and must be a string' }, { status: 400 });
    }

    // 3. Delete from Firestore
    try {
        const app = getFirebaseAdmin();
        const db = getFirestore(app);

        const docRef = db.collection('newsletter_updates').doc(source_id);
        const doc = await docRef.get();

        if (!doc.exists) {
            return NextResponse.json({ status: 'ok', deleted: source_id, existed: false }, { status: 200 });
        }

        await docRef.delete();

        return NextResponse.json({ status: 'ok', deleted: source_id, existed: true }, { status: 200 });
    } catch (error) {
        console.error('Firestore delete failed:', error);
        return NextResponse.json({ error: 'Internal server error' }, { status: 500 });
    }
}
