/**
 * Confirm Interview API
 * POST: Confirm interview and send confirmation email
 */

import { NextRequest, NextResponse } from "next/server";
import { getStaffSession } from "@/lib/staff-session";
import { prisma } from "@/lib/db";

import { getDataSource } from "@/lib/data-source";
import { convexMutation } from "@/lib/convex-client";

export async function POST(
  req: NextRequest,
  { params }: { params: { id: string } },
) {
  try {
    // Verify staff authentication
    const session = await getStaffSession();
    if (!session) {
      return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
    }

    // Fetch booking
    const booking = await prisma.interview_bookings.findUnique({
      where: { id: params.id },
    });

    if (!booking) {
      return NextResponse.json({ error: "Booking not found" }, { status: 404 });
    }

    // Validation
    if (!booking.meeting_link) {
      return NextResponse.json(
        { error: "Meeting link is required before confirming" },
        { status: 400 },
      );
    }

    if (booking.status === "confirmed") {
      return NextResponse.json(
        { error: "Interview is already confirmed" },
        { status: 400 },
      );
    }

    // Update booking status
    const updateData = {
      status: "confirmed",
      confirmed_at: new Date(),
      confirmed_by: session.email,
      confirmed_date: booking.preferred_date,
      confirmed_time: booking.preferred_time,
      updated_at: new Date(),
    };

    // TODO: Send confirmation email
    // await sendInterviewConfirmationEmail({
    //   applicantEmail: booking.applicant_email,
    //   applicantName: booking.applicant_name,
    //   jobTitle: '...', // Fetch from job
    //   interviewDate: booking.confirmed_date,
    //   interviewTime: booking.confirmed_time,
    //   meetingLink: booking.meeting_link,
    //   meetingPlatform: booking.meeting_platform,
    //   meetingId: booking.meeting_id,
    //   meetingPassword: booking.meeting_password,
    //   timezone: booking.timezone,
    //   language: 'en', // Detect from application
    // });

    return NextResponse.json({
      success: true,
      message:
        "Interview confirmed successfully. Confirmation email sent to applicant.",
    });
  } catch (error: any) {
    console.error("Error confirming interview:", error);
    return NextResponse.json(
      { error: "Failed to confirm interview", details: error.message },
      { status: 500 },
    );
  }
}
