import { NextResponse } from "next/server";
import { redirect } from "next/navigation";

import { canAccessApi, canAccessPage, getDefaultPathForRole } from "@/config/access-control";
import { type SessionUser, verifySessionToken, AUTH_COOKIE_NAME } from "@/lib/auth";
import { getSessionUser } from "@/lib/auth-server";

export async function requireAuthorizedPageUser(pathname: string): Promise<SessionUser> {
  const user = await getSessionUser();

  if (!user) {
    redirect("/login");
  }

  if (!canAccessPage(user.role, pathname)) {
    redirect(getDefaultPathForRole(user.role));
  }

  return user;
}

export function requireApiAccess(request: Request) {
  const authHeader = request.headers.get("authorization") ?? "";
  const bearerToken = authHeader.startsWith("Bearer ") ? authHeader.slice("Bearer ".length).trim() : null;
  const cookieHeader = request.headers.get("cookie") ?? "";
  const cookieToken = cookieHeader
    .split(";")
    .map((part) => part.trim())
    .find((part) => part.startsWith(`${AUTH_COOKIE_NAME}=`))
    ?.slice(`${AUTH_COOKIE_NAME}=`.length);
  const token = bearerToken || cookieToken;

  const user = token ? verifySessionToken(token) : null;

  if (!user) {
    return {
      ok: false as const,
      response: NextResponse.json({ message: "Unauthorized" }, { status: 401 })
    };
  }

  const pathname = new URL(request.url).pathname;
  if (!canAccessApi(user.role, pathname, request.method)) {
    return {
      ok: false as const,
      response: NextResponse.json({ message: "Forbidden" }, { status: 403 })
    };
  }

  return {
    ok: true as const,
    user
  };
}
