import type { z } from "zod";
import type { RealtimeChannelDescriptor } from "./realtime-channel";

export async function authorize(
  descriptor: RealtimeChannelDescriptor<string, z.ZodType>,
  params: Record<string, string>,
  user: { userId: string; roles: string[] } | null,
): Promise<boolean> {
  const scope = descriptor.scope;

  if (scope === "public") return true;
  if (scope === "authenticated") return user !== null;

  if (typeof scope === "object" && "role" in scope) {
    return user !== null && user.roles.includes(scope.role);
  }
  if (typeof scope === "object" && "userScoped" in scope) {
    return user !== null && params.userId === user.userId;
  }

  return false;
}
