import { Collection, Result } from "@repo/rdx-utils";
import { Filter } from "./Filter";

export interface IFilterCollection extends Collection<Filter> {
  findByField(field: string): Filter | undefined;
  removeByField(field: string): void;
  toObject(): Record<string, any>;
}

export class FilterCollection extends Collection<Filter> implements IFilterCollection {
  static create(filters?: Filter[]): Result<FilterCollection> {
    return Result.ok<FilterCollection>(new FilterCollection(filters));
  }

  protected constructor(initialValues?: Filter[]) {
    super(initialValues, undefined);
  }

  public findByField(field: string): Filter | undefined {
    return this.find((filter) => filter.field === field);
  }

  public removeByField(field: string): void {
    const indexFound = this.getAll().findIndex((filter) => filter.field === field);
    if (indexFound > -1) {
      this.removeByIndex(indexFound);
    }
  }

  public toObject(): Record<string, any> {
    return this.getAll().map((filter: Filter) => filter.toObject());
  }
}
