/**
 * Auto-generated by ${VOCAB.factory}
 * IntelligenceBrief API Routes
 */

import { NextRequest, NextResponse } from 'next/server';
import { prisma } from '@/lib/db';
import { VOCAB } from '@/lib/white-label/constants';

export const dynamic = 'force-dynamic';


// GET - List all IntelligenceBrief records
export async function GET(request: NextRequest) {
  try {
    const searchParams = request.nextUrl.searchParams;
    const page = parseInt(searchParams.get('page') || '1');
    const limit = parseInt(searchParams.get('limit') || '20');
    const skip = (page - 1) * limit;

    const [items, total] = await Promise.all([
      prisma.intelligenceBrief.findMany({
        skip,
        take: limit,
        orderBy: { generatedAt: 'desc' },
      }),
      prisma.intelligenceBrief.count(),
    ]);

    return NextResponse.json({
      data: items,
      pagination: {
        page,
        limit,
        total,
        totalPages: Math.ceil(total / limit),
      },
    });
  } catch (error) {
    console.error('Error fetching IntelligenceBrief:', error);
    return NextResponse.json(
      { error: 'Failed to fetch IntelligenceBrief records' },
      { status: 500 }
    );
  }
}


// POST - Create a new IntelligenceBrief
export async function POST(request: NextRequest) {
  try {
    const body = await request.json();
    
    // Validate required fields
    const required = ['period', 'executiveSummary', 'keyMetrics', 'topWins', 'topConcerns', 'recommendedActions'];
    const missing = required.filter(field => !(field in body));
    if (missing.length > 0) {
      return NextResponse.json(
        { error: `Missing required fields: ${missing.join(', ')}` },
        { status: 400 }
      );
    }

    const intelligenceBrief = await prisma.intelligenceBrief.create({
      data: body,
    });

    return NextResponse.json(intelligenceBrief, { status: 201 });
  } catch (error) {
    console.error('Error creating IntelligenceBrief:', error);
    return NextResponse.json(
      { error: 'Failed to create IntelligenceBrief' },
      { status: 500 }
    );
  }
}
