import { NextResponse } from "next/server";

export type Role = "PATIENT" | "ASSISTANT" | "THERAPIST";

export interface RouteConfig {
  requiredRoles?: Role[];
  requireAuth?: boolean;
}

const ROUTES: Record<string, RouteConfig> = {
  "/dashboard/terapeuta": {
    requiredRoles: ["THERAPIST"],
    requireAuth: true,
  },
  "/dashboard/asistente": {
    requiredRoles: ["ASSISTANT", "THERAPIST"],
    requireAuth: true,
  },
  "/api/dashboard": {
    requireAuth: true,
  },
  "/api/payments/validate": {
    requiredRoles: ["ASSISTANT", "THERAPIST"],
    requireAuth: true,
  },
  "/api/clinical-notes": {
    requiredRoles: ["THERAPIST"],
    requireAuth: true,
  },
};

export function checkRouteAccess(
  pathname: string,
  userRole: Role | null
): { allowed: boolean; reason?: string } {
  const routeConfig = ROUTES[pathname];

  if (!routeConfig) {
    return { allowed: true };
  }

  if (routeConfig.requireAuth && !userRole) {
    return { allowed: false, reason: "Authentication required" };
  }

  if (routeConfig.requiredRoles && userRole && !routeConfig.requiredRoles.includes(userRole)) {
    return { allowed: false, reason: "Insufficient permissions" };
  }

  return { allowed: true };
}

export function createAuthResponse(redirectUrl?: string): NextResponse {
  if (redirectUrl) {
    return NextResponse.redirect(
      new URL(redirectUrl, process.env.NEXT_PUBLIC_APP_URL || "http://localhost:3000")
    );
  }
  return NextResponse.redirect(
    new URL("/login", process.env.NEXT_PUBLIC_APP_URL || "http://localhost:3000")
  );
}
