import { Result } from "../../Result";
import { ValueObject } from "../../ValueObject";

export interface IFilterProps {
  operator: string;
  field?: string;
  value: any;
}

export interface IFilter {
  operator: string;
  field?: string;
  value: any;

  toString(): string;
  toObject(): Record<string, string>;
}

export class Filter extends ValueObject<IFilterProps> implements IFilter {
  public static create(filterProps: IFilterProps): Result<Filter> {
    // Validación de props
    const valid = this.validate(filterProps);
    if (valid.isFailure) {
      return Result.fail(valid.error);
    }

    return Result.ok<Filter>(
      new Filter({
        ...filterProps,
        operator: Filter.sanitizeOperator(filterProps.operator),
      })
    );
  }

  protected static validate(filter: any): Result<Filter> {
    return Result.ok(filter);
  }

  protected static sanitizeOperator(operator: string): string {
    return operator.toUpperCase().trim();
  }

  protected constructor(props: IFilterProps) {
    super(props);
  }

  get field(): string | undefined {
    return this.props.field;
  }

  get operator(): string {
    return this.props.operator;
  }

  get value(): any {
    return this.props.value;
  }

  public toString(): string {
    return `${this.field} [${this.operator}] ${this.value}`;
  }

  public toObject(): Record<string, string> {
    return {
      operator: String(this.operator),
      field: String(this.field),
      value: this.value,
    };
  }

  public toJSON(): string {
    return this.toString();
  }

  public toPrimitive(): string {
    return this.toString();
  }
}
