/**
 * Cancel Interview API
 * POST: Cancel interview and send cancellation 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 });
    }

    const body = await req.json();
    const { reason } = body;

    if (!reason) {
      return NextResponse.json(
        { error: "Cancellation reason is required" },
        { status: 400 },
      );
    }

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

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

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

    // Update booking status
    const updateData = {
      status: "cancelled",
      cancelled_at: new Date(),
      cancelled_by: session.email,
      cancellation_reason: reason,
      updated_at: new Date(),
    };

    // TODO: Send cancellation email
    // await sendInterviewCancellationEmail({
    //   applicantEmail: booking.applicant_email,
    //   applicantName: booking.applicant_name,
    //   jobTitle: '...', // Fetch from job
    //   cancellationReason: reason,
    //   canReschedule: true,
    //   language: 'en',
    // });

    return NextResponse.json({
      success: true,
      message:
        "Interview cancelled successfully. Notification email sent to applicant.",
    });
  } catch (error: any) {
    console.error("Error cancelling interview:", error);
    return NextResponse.json(
      { error: "Failed to cancel interview", details: error.message },
      { status: 500 },
    );
  }
}
