/**
 * Staff Resume Download API
 * GET: Download applicant's CV - STAFF+
 */

import { NextRequest, NextResponse } from "next/server";
import { getStaffSession } from "@/lib/staff-auth";
import { logger } from "@/lib/logger";
import { convexQuery } from "@/lib/convex-client";

async function verifyStaffAuth(
  requiredRoles: string[] = ["STAFF", "ADMIN", "SUPER_ADMIN"],
) {
  const user = await getStaffSession();

  if (!user) {
    return {
      error: NextResponse.json({ error: "Unauthorized" }, { status: 401 }),
    };
  }

  if (!requiredRoles.includes(user.role)) {
    return {
      error: NextResponse.json(
        { error: "Insufficient permissions" },
        { status: 403 },
      ),
    };
  }

  return { user, role: user.role };
}

/**
 * GET /api/staff/applications/[id]/download-cv
 * Download applicant's resume PDF
 */
export async function GET(
  request: NextRequest,
  { params }: { params: { id: string } },
) {
  const authResult = await verifyStaffAuth();
  if ("error" in authResult) return authResult.error;

  const { id } = params;

  try {
    // Get application record to find CV storage ID
    const application = (await convexQuery(
      "careers/queries:getJobApplication",
      {
        id,
      },
    )) as {
      cv_storage_id?: string;
      cv_filename?: string;
      applicant_name?: string;
      cv_path?: string;
    } | null;

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

    const storageId = application.cv_storage_id;
    if (!storageId) {
      return NextResponse.json(
        { error: "CV not found for this application" },
        { status: 404 },
      );
    }

    // Get file URL from Convex storage
    const fileUrl = (await convexQuery("storage/queries:getFileUrl", {
      storageId,
    })) as string | null;

    if (!fileUrl) {
      logger.error("Failed to get CV URL from Convex storage", { storageId });
      return NextResponse.json(
        { error: "Failed to download resume" },
        { status: 500 },
      );
    }

    // Download the file from Convex storage URL
    const fileResponse = await fetch(fileUrl);
    if (!fileResponse.ok) {
      logger.error("Failed to download CV from Convex storage URL", {
        storageId,
        status: fileResponse.status,
      });
      return NextResponse.json(
        { error: "Failed to download resume" },
        { status: 500 },
      );
    }

    const buffer = Buffer.from(await fileResponse.arrayBuffer());

    // Log the download for audit purposes
    logger.info("CV downloaded by staff", {
      applicationId: id,
      applicantName: application.applicant_name,
      storageId,
      downloadedBy: authResult.user.email,
    });

    const filename = application.cv_filename || "resume.pdf";

    // Return file with appropriate headers
    return new NextResponse(buffer, {
      status: 200,
      headers: {
        "Content-Type": "application/pdf",
        "Content-Disposition": `attachment; filename="${filename}"`,
        "Content-Length": buffer.length.toString(),
      },
    });
  } catch (error) {
    logger.error("Staff CV download error", error);
    return NextResponse.json(
      { error: "Internal server error" },
      { status: 500 },
    );
  }
}
