import { NextRequest, NextResponse } from "next/server";
import { prisma } from "@/infrastructure/db/prisma";

const AUTH_TOKEN_COOKIE = "gloria_auth_token";
const AUTH_USER_COOKIE = "gloria_user_id";

export async function withAuth(
  request: NextRequest,
  requiredRoles?: string[]
): Promise<{ user: any; authorized: boolean } | NextResponse> {
  try {
    const cookieHeader = request.headers.get("cookie");
    const token = cookieHeader
      ?.split(";")
      .find((c) => c.trim().startsWith(`${AUTH_TOKEN_COOKIE}=`))
      ?.split("=")[1];
    const userId = cookieHeader
      ?.split(";")
      .find((c) => c.trim().startsWith(`${AUTH_USER_COOKIE}=`))
      ?.split("=")[1];

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

    const user = await prisma.user.findUnique({
      where: { id: userId },
    });

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

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

    return { user, authorized: true };
  } catch (error) {
    console.error("Auth middleware error:", error);
    return NextResponse.json({ error: "Internal server error" }, { status: 500 });
  }
}

export function setAuthCookies(
  response: NextResponse,
  token: string,
  userId: string
): NextResponse {
  response.cookies.set(AUTH_TOKEN_COOKIE, token, {
    httpOnly: true,
    secure: process.env.NODE_ENV === "production",
    sameSite: "strict",
    maxAge: 60 * 60 * 24 * 7, // 7 days
    path: "/",
  });

  response.cookies.set(AUTH_USER_COOKIE, userId, {
    httpOnly: true,
    secure: process.env.NODE_ENV === "production",
    sameSite: "strict",
    maxAge: 60 * 60 * 24 * 7, // 7 days
    path: "/",
  });

  return response;
}

export function clearAuthCookies(response: NextResponse): NextResponse {
  response.cookies.delete(AUTH_TOKEN_COOKIE);
  response.cookies.delete(AUTH_USER_COOKIE);
  return response;
}

export const ROLES = {
  PATIENT: "PATIENT",
  ASSISTANT: "ASSISTANT",
  THERAPIST: "THERAPIST",
};
