/**
 * Staff Interview Booking Detail API
 * GET: Get booking details
 * PATCH: Update booking
 */

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

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

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

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

    // Enrich with job and application data
    let jobTitle = null;
    let jobTitleAr = null;
    let applicantCvPath = null;
    let applicationStatus = null;
    let submittedAt = null;

    // Fetch job details
    if (booking.job_id) {
      try {
        const job = await prisma.jobs.findUnique({
          where: { id: booking.job_id },
          select: { title_translations: true },
        });

        if (job && job.title_translations) {
          const translations = job.title_translations as Record<string, string>;
          jobTitle = translations.en ?? null;
          jobTitleAr = translations.ar ?? null;
        }
      } catch {
        // Job may not exist in Prisma yet
      }
    }

    // Fetch application details
    if (booking.application_id) {
      try {
        const application = await prisma.job_applications.findUnique({
          where: { id: booking.application_id },
          select: { status: true, submitted_at: true, applicant_cv_path: true },
        });

        if (application) {
          applicationStatus = application.status;
          submittedAt = application.submitted_at;
          applicantCvPath = application.applicant_cv_path;
        }
      } catch {
        // Application may not exist in Prisma yet
      }
    }

    const enrichedBooking = {
      id: booking.id,
      applicationId: booking.application_id,
      jobId: booking.job_id,
      applicantName: booking.applicant_name,
      applicantEmail: booking.applicant_email,
      applicantPhone: booking.applicant_phone,
      preferredDate: booking.preferred_date,
      preferredTime: booking.preferred_time,
      timezone: booking.timezone,
      durationMinutes: booking.duration_minutes,
      confirmedDate: booking.confirmed_date,
      confirmedTime: booking.confirmed_time,
      meetingLink: booking.meeting_link,
      meetingPlatform: booking.meeting_platform,
      meetingId: booking.meeting_id,
      meetingPassword: booking.meeting_password,
      status: booking.status,
      applicantNotes: booking.applicant_notes,
      staffNotes: booking.staff_notes,
      assignedTo: booking.assigned_to,
      confirmedAt: booking.confirmed_at,
      confirmedBy: booking.confirmed_by,
      cancelledAt: booking.cancelled_at,
      cancelledBy: booking.cancelled_by,
      cancellationReason: booking.cancellation_reason,
      createdAt: booking.created_at,
      updatedAt: booking.updated_at,
      // Enriched data
      jobTitle,
      jobTitleAr,
      applicantCvPath,
      applicationStatus,
      submittedAt,
    };

    return NextResponse.json({
      success: true,
      booking: enrichedBooking,
    });
  } catch (error: any) {
    console.error("Error fetching booking details:", error);
    return NextResponse.json(
      { error: "Failed to fetch booking details", details: error.message },
      { status: 500 },
    );
  }
}

export async function PATCH(
  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 {
      status,
      confirmedDate,
      confirmedTime,
      meetingLink,
      meetingPlatform,
      meetingId,
      meetingPassword,
      staffNotes,
      assignedTo,
      cancellationReason,
    } = body;

    // Build update data
    const updateData: any = {
      updated_at: new Date(),
    };

    if (status) {
      updateData.status = status;

      // Set timestamps based on status
      if (status === "confirmed") {
        updateData.confirmed_at = new Date();
        updateData.confirmed_by = session.email;
      } else if (status === "cancelled") {
        updateData.cancelled_at = new Date();
        updateData.cancelled_by = session.email;
      }
    }

    if (confirmedDate !== undefined) {
      updateData.confirmed_date = confirmedDate
        ? new Date(confirmedDate)
        : null;
    }
    if (confirmedTime !== undefined) {
      updateData.confirmed_time = confirmedTime;
    }
    if (meetingLink !== undefined) {
      updateData.meeting_link = meetingLink;
    }
    if (meetingPlatform !== undefined) {
      updateData.meeting_platform = meetingPlatform;
    }
    if (meetingId !== undefined) {
      updateData.meeting_id = meetingId;
    }
    if (meetingPassword !== undefined) {
      updateData.meeting_password = meetingPassword;
    }
    if (staffNotes !== undefined) {
      updateData.staff_notes = staffNotes;
    }
    if (assignedTo !== undefined) {
      updateData.assigned_to = assignedTo;
    }
    if (cancellationReason !== undefined) {
      updateData.cancellation_reason = cancellationReason;
    }

    // Update in database
    const updated = await prisma.interview_bookings.update({
      where: { id: params.id },
      data: updateData,
    });

    if (!updated) {
      throw new Error("Failed to update booking");
    }

    // Send email notifications based on status change
    if (status) {
      const booking = await prisma.interview_bookings.findUnique({
        where: { id: params.id },
      });

      if (booking) {
        // Import email service (you'll need to create these functions)
        // await sendInterviewStatusEmail(booking, status);
      }
    }

    return NextResponse.json({
      success: true,
      message: "Booking updated successfully",
    });
  } catch (error: any) {
    console.error("Error updating booking:", error);
    return NextResponse.json(
      { error: "Failed to update booking", details: error.message },
      { status: 500 },
    );
  }
}
