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 ListUsersByRoleInput {
  roleId: string;
}

/**
 * Function: listUsersByRole
 *
 * Returns the current ACTIVE users assigned to a role.
 * Excludes PENDING and INACTIVE users so callers (e.g. approval routing)
 * receive only the membership that can act on the system right now.
 */
export async function run(db: ReadonlyDB<DB>, input: ListUsersByRoleInput) {
  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)
    .where("User.status", "=", "ACTIVE")
    .execute();

  return ok({ users });
}
