import { Role } from "@prisma/client";

export type Requester = { id: string; role: Role };

export type TodoAccessShape = {
  assignees: Array<{ id: string; managerId: string | null }>;
  createdBy: { id: string };
};

export function canAccessTodo(requester: Requester, todo: TodoAccessShape): boolean {
  // Policy: end users never access app endpoints
  if (requester.role === Role.USER) return false;

  const isAssignee = !!todo.assignees.find((a) => a.id === requester.id);
  const isCreator = todo.createdBy.id === requester.id;
  const isManagerOfAssignee = !!todo.assignees.find((a) => a.managerId === requester.id);

  if (requester.role === Role.ADMIN) {
    return isAssignee; // Admins can only access Todos assigned to themselves
  }
  if (requester.role === Role.MANAGER) {
    return isAssignee || isManagerOfAssignee || isCreator;
  }
  return false;
}

export function validateCommentAuthor(requesterId: string, comment: { userId: string }) {
  if (comment.userId !== requesterId) {
    const err: any = new Error("Only the author can modify this comment");
    err.status = 403;
    throw err;
  }
}
