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

export interface ListRolePermissionsByRoleInput {
  roleId: string;
}

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

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

  const permissions = await db
    .selectFrom("RolePermission")
    .innerJoin("Permission", "Permission.id", "RolePermission.permissionId")
    .selectAll("Permission")
    .where("RolePermission.roleId", "=", input.roleId)
    .execute();

  return ok({ permissions });
}
