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

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

/**
 * Function: revokePermissionFromRole
 *
 * Removes a permission from a role.
 * Throws an error if the assignment does not exist.
 *
 * Note: Permissions for affected users are recomputed asynchronously via executor.
 */
export async function run(db: Transaction, input: RevokePermissionFromRoleInput) {
  const role = await db
    .selectFrom("Role")
    .selectAll()
    .where("id", "=", input.roleId)
    .executeTakeFirst();

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

  const permission = await db
    .selectFrom("Permission")
    .selectAll()
    .where("id", "=", input.permissionId)
    .executeTakeFirst();

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

  const existingAssignment = await db
    .selectFrom("RolePermission")
    .selectAll()
    .where("roleId", "=", input.roleId)
    .where("permissionId", "=", input.permissionId)
    .forUpdate()
    .executeTakeFirst();

  if (!existingAssignment) {
    return err(
      new AssignmentNotFoundError(`Role ${input.roleId} -> Permission ${input.permissionId}`),
    );
  }

  // Permission recomputation for affected users is handled asynchronously by executor
  await db
    .deleteFrom("RolePermission")
    .where("id", "=", existingAssignment.id)
    .returningAll()
    .executeTakeFirst();

  return ok({});
}
