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

export interface ListUserRolesByUserInput {
  userId: string;
}

export async function run(db: ReadonlyDB<DB>, input: ListUserRolesByUserInput) {
  const user = await db
    .selectFrom("User")
    .selectAll()
    .where("id", "=", input.userId)
    .executeTakeFirst();

  if (!user) {
    return err(new UserNotFoundError(input.userId));
  }

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

  return ok({ roles });
}
