import { err, ok, type ReadonlyDB } from "@tailor-platform/erp-kit/core";
import type { DB } from "../generated/kysely-tailordb";
import { RoleNotFoundError } from "../lib/errors.generated";

export interface ListUserRolesByRoleInput {
  roleId: string;
}

export async function run(db: ReadonlyDB<DB>, input: ListUserRolesByRoleInput) {
  const role = await db
    .selectFrom("Role")
    .selectAll()
    .where("id", "=", input.roleId)
    .executeTakeFirst();

  if (!role) {
    return err(new RoleNotFoundError(input.roleId));
  }

  const users = await db
    .selectFrom("UserRole")
    .innerJoin("User", "User.id", "UserRole.userId")
    .selectAll("User")
    .where("UserRole.roleId", "=", input.roleId)
    .execute();

  return ok({ users });
}
