/**
 * Send Interview Invite API
 * POST: Generate token and send interview invitation email
 */

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

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 application details from database
    console.log("Fetching application:", params.id);

    const application = await prisma.job_applications.findUnique({
      where: { id: params.id },
      select: {
        id: true,
        job_id: true,
        applicant_name: true,
        applicant_email: true,
        status: true,
        jobs: {
          select: {
            id: true,
            title_translations: true,
          },
        },
      },
    });

    if (!application) {
      console.error("No application found with ID:", params.id);
      return NextResponse.json(
        { error: "Application not found" },
        { status: 404 },
      );
    }

    console.log("Application found:", {
      id: application.id,
      name: application.applicant_name,
      email: application.applicant_email,
      status: application.status,
      hasJob: !!application.jobs,
    });

    // Validate application status
    if (
      application.status !== "shortlisted" &&
      application.status !== "interview_scheduled"
    ) {
      return NextResponse.json(
        {
          error:
            "Application must be shortlisted before sending interview invite",
        },
        { status: 400 },
      );
    }

    // Check if token already exists and is not expired
    const existingToken = await prisma.interview_booking_tokens.findFirst({
      where: {
        application_id: application.id,
        is_revoked: false,
        used_at: null,
        expires_at: {
          gt: new Date(),
        },
      },
    });

    if (existingToken) {
      return NextResponse.json(
        {
          error:
            "Active interview invitation already sent. Token expires at: " +
            existingToken.expires_at,
        },
        { status: 400 },
      );
    }

    // Generate secure token (URL-safe)
    const tokenString = randomBytes(32).toString("base64url");

    // Token expires in 72 hours (3 days)
    const expiresAt = new Date(Date.now() + 72 * 60 * 60 * 1000);

    // Save token to both databases
    console.log("💾 Saving token to database...");

    const tokenData = {
      token: tokenString,
      application_id: application.id,
      job_id: application.job_id,
      applicant_email: application.applicant_email,
      expires_at: expiresAt,
      is_revoked: false,
      created_at: new Date(),
      updated_at: new Date(),
    };

    console.log("Token data:", {
      ...tokenData,
      token: tokenData.token.substring(0, 20) + "...",
    });

    const savedToken = await prisma.interview_booking_tokens.create({
      data: tokenData,
    });

    if (!savedToken) {
      console.error("Failed to save token to database");
      throw new Error("Failed to create booking token");
    }

    console.log("Token saved successfully");

    // Generate booking URL
    const bookingUrl = `${process.env.NEXT_PUBLIC_BASE_URL || "http://localhost:9000"}/en/careers/interview/schedule?token=${tokenString}`;

    // Update application status

    // Send interview invitation email to applicant
    try {
      const emailSent = await sendInterviewInvitationEmail(
        application.applicant_email,
        application.applicant_name,
        (application.jobs?.title_translations as Record<string, string> | null)
          ?.en || "Position",
        (application.jobs?.title_translations as Record<string, string> | null)
          ?.ar || "المنصب",
        tokenString,
        expiresAt.toISOString(),
        "en", // TODO: Detect from application preferences or use default
      );

      if (!emailSent) {
        console.error(
          "Failed to send interview invitation email, but token was created",
        );
        // Don't fail the request - token is created, email failure is non-critical
      }
    } catch (emailError) {
      console.error("Error sending interview invitation email:", emailError);
      // Don't fail the request - token is created, email failure is non-critical
    }

    // Create audit log

    return NextResponse.json({
      success: true,
      message: "Interview invitation sent successfully",
      bookingUrl, // For staff reference
      expiresAt,
    });
  } catch (error: any) {
    console.error("❌ Error sending interview invite:", error);
    console.error("Error stack:", error.stack);
    console.error("Error details:", {
      name: error.name,
      message: error.message,
      code: error.code,
    });

    return NextResponse.json(
      {
        error: "Failed to send interview invite",
        details: error.message,
        errorType: error.name,
        hint: "Check server logs for details",
      },
      { status: 500 },
    );
  }
}
