import { NextRequest } from "next/server";
import jwt from "jsonwebtoken";
import { corePool } from "@/lib/db/mysql";

type RecruiterTokenPayload = {
  recruiter_id: number;
  company_id: number;
};

export async function requireRecruiter(req: NextRequest) {
  const authHeader = req.headers.get("authorization");

  if (!authHeader || !authHeader.startsWith("Bearer ")) {
    throw new Error("unauthorized");
  }

  const token = authHeader.replace("Bearer ", "");

  let payload: RecruiterTokenPayload;

  try {
    payload = jwt.verify(
      token,
      process.env.JWT_SECRET as string
    ) as RecruiterTokenPayload;
  } catch {
    throw new Error("unauthorized");
  }

  const [[recruiter]]: any = await corePool.query(
    `
    SELECT r.id, r.company_id, r.is_active
    FROM recruiters r
    WHERE r.id = ?
    `,
    [payload.recruiter_id]
  );

  if (!recruiter || recruiter.is_active !== 1) {
    throw new Error("unauthorized");
  }

  return recruiter as {
    id: number;
    company_id: number;
  };
}
