import { NextRequest, NextResponse } from 'next/server';
import { prisma, prismaAuth } from '@/lib/db';
import { auth } from '@/app/api/auth/[...nextauth]/route';

export async function POST(
  request: NextRequest,
  { params }: { params: Promise<{ id: string }> }
) {
  try {
    // Check authentication
    const session = await auth();
    if (!session?.user?.id) {
      return NextResponse.json(
        { error: 'Authentication required. Please sign in to identify faces.' },
        { status: 401 }
      );
    }

    // Check write access
    if (!session.user.hasWriteAccess) {
      return NextResponse.json(
        { error: 'Write access required. You need write access to identify faces. Please contact an administrator.' },
        { status: 403 }
      );
    }

    const { id } = await params;
    const faceId = parseInt(id, 10);
    
    if (isNaN(faceId)) {
      return NextResponse.json(
        { error: 'Invalid face ID' },
        { status: 400 }
      );
    }

    const body = await request.json();
    const { personId, firstName, lastName, middleName, maidenName, dateOfBirth } = body;

    let finalFirstName: string;
    let finalLastName: string;
    let finalMiddleName: string | null = null;
    let finalMaidenName: string | null = null;
    let finalDateOfBirth: Date | null = null;

    // If personId is provided, fetch person data from database
    if (personId) {
      const person = await prisma.person.findUnique({
        where: { id: parseInt(personId, 10) },
      });

      if (!person) {
        return NextResponse.json(
          { error: 'Person not found' },
          { status: 404 }
        );
      }

      finalFirstName = person.first_name;
      finalLastName = person.last_name;
      finalMiddleName = person.middle_name;
      finalMaidenName = person.maiden_name;
      finalDateOfBirth = person.date_of_birth;
    } else {
      // Validate required fields for new person
      if (!firstName || !lastName) {
        return NextResponse.json(
          { error: 'First name and last name are required' },
          { status: 400 }
        );
      }

      finalFirstName = firstName;
      finalLastName = lastName;
      finalMiddleName = middleName || null;
      finalMaidenName = maidenName || null;
      
      // Parse date of birth if provided
      const dob = dateOfBirth ? new Date(dateOfBirth) : null;
      if (dateOfBirth && dob && isNaN(dob.getTime())) {
        return NextResponse.json(
          { error: 'Invalid date of birth' },
          { status: 400 }
        );
      }
      finalDateOfBirth = dob;
    }

    // Check if face exists (use read client for this - from punimtag database)
    const face = await prisma.face.findUnique({
      where: { id: faceId },
      include: { Person: true },
    });

    if (!face) {
      return NextResponse.json(
        { error: 'Face not found' },
        { status: 404 }
      );
    }

    const userId = parseInt(session.user.id, 10);
    if (isNaN(userId)) {
      return NextResponse.json(
        { error: 'Invalid user session' },
        { status: 401 }
      );
    }

    // Check if there's already a pending identification for this face by this user
    // Use auth client (connects to punimtag_auth database)
    const existingPending = await prismaAuth.pendingIdentification.findFirst({
      where: {
        faceId,
        userId,
        status: 'pending',
      },
    });

    if (existingPending) {
      // Update existing pending identification
      const updated = await prismaAuth.pendingIdentification.update({
        where: { id: existingPending.id },
        data: {
          firstName: finalFirstName,
          lastName: finalLastName,
          middleName: finalMiddleName,
          maidenName: finalMaidenName,
          dateOfBirth: finalDateOfBirth,
        },
      });

      return NextResponse.json({
        message: 'Identification updated and pending approval',
        pendingIdentification: updated,
      });
    }

    // Create new pending identification
    const pendingIdentification = await prismaAuth.pendingIdentification.create({
      data: {
        faceId,
        userId,
        firstName: finalFirstName,
        lastName: finalLastName,
        middleName: finalMiddleName,
        maidenName: finalMaidenName,
        dateOfBirth: finalDateOfBirth,
        status: 'pending',
      },
    });

    return NextResponse.json({
      message: 'Identification submitted and pending approval',
      pendingIdentification,
    });
  } catch (error: any) {
    console.error('Error identifying face:', error);
    
    // Handle unique constraint violation
    if (error.code === 'P2002') {
      return NextResponse.json(
        { error: 'A person with these details already exists' },
        { status: 409 }
      );
    }

    return NextResponse.json(
      { error: 'Failed to identify face', details: error.message },
      { status: 500 }
    );
  }
}

