import { NextRequest, NextResponse } from 'next/server';
import { prisma } from '@/lib/db';

export async function GET(request: NextRequest) {
  try {
    const people = await prisma.person.findMany({
      orderBy: [
        { first_name: 'asc' },
        { last_name: 'asc' },
      ],
      select: {
        id: true,
        first_name: true,
        last_name: true,
        middle_name: true,
        maiden_name: true,
        date_of_birth: true,
        created_date: true,
      },
    });

    // Transform snake_case to camelCase for frontend
    const transformedPeople = people.map((person) => ({
      id: person.id,
      firstName: person.first_name,
      lastName: person.last_name,
      middleName: person.middle_name,
      maidenName: person.maiden_name,
      dateOfBirth: person.date_of_birth,
      createdDate: person.created_date,
    }));

    return NextResponse.json({ people: transformedPeople }, { status: 200 });
  } catch (error: any) {
    // Handle corrupted data errors (P2023)
    if (error?.code === 'P2023' || error?.message?.includes('Conversion failed')) {
      console.warn('Corrupted person data detected, attempting fallback query');
      try {
        // Try with minimal fields first
        const people = await prisma.person.findMany({
          select: {
            id: true,
            first_name: true,
            last_name: true,
            // Exclude potentially corrupted optional fields
          },
          orderBy: [
            { first_name: 'asc' },
            { last_name: 'asc' },
          ],
        });

        // Transform snake_case to camelCase for frontend
        const transformedPeople = people.map((person) => ({
          id: person.id,
          firstName: person.first_name,
          lastName: person.last_name,
          middleName: null,
          maidenName: null,
          dateOfBirth: null,
          createdDate: null,
        }));

        return NextResponse.json({ people: transformedPeople }, { status: 200 });
      } catch (fallbackError: any) {
        console.error('Fallback person query also failed:', fallbackError);
        return NextResponse.json(
          { error: 'Failed to fetch people', details: fallbackError.message },
          { status: 500 }
        );
      }
    }

    console.error('Error fetching people:', error);
    return NextResponse.json(
      { error: 'Failed to fetch people', details: error.message },
      { status: 500 }
    );
  }
}

