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

export interface RevokePermissionFromRoleInput {
  roleId: string;
  permission: string;
}

/**
 * Function: revokePermissionFromRole
 *
 * Removes a permission key from a role's permissions array.
 */
export async function run(db: Transaction, input: RevokePermissionFromRoleInput) {
  const role = await db
    .selectFrom("Role")
    .selectAll()
    .where("id", "=", input.roleId)
    .forUpdate()
    .executeTakeFirst();

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

  const currentPermissions = role.permissions ?? [];

  if (!currentPermissions.includes(input.permission)) {
    return err(new PermissionNotFoundError(input.permission));
  }

  const updatedRole = await db
    .updateTable("Role")
    .set({
      permissions: currentPermissions.filter((p) => p !== input.permission),
    })
    .where("id", "=", input.roleId)
    .returningAll()
    .executeTakeFirstOrThrow();

  return ok({ role: updatedRole });
}
