import { ValueObject } from "@/core/common/domain";
import { Result } from "@repo/rdx-utils";

interface IInvoiceStatusProps {
  value: string;
}

export class InvoiceStatus extends ValueObject<IInvoiceStatusProps> {
  private static readonly ALLOWED_STATUSES = [
    "borrador",
    "enviada",
    "aceptada",
    "registrada",
    "rechazada",
    "cerrada",
    "error",
  ];

  private static readonly TRANSITIONS: Record<string, string[]> = {
    borrador: ["enviada"],
    enviada: ["aceptada", "registrada", "rechazada", "error"],
    aceptada: ["registrada"],
    registrada: ["cerrada"],
    rechazada: ["cerrada"],
    error: ["borrador"],
    cerrada: [],
  };

  static create(value: string): Result<InvoiceStatus, Error> {
    if (!this.ALLOWED_STATUSES.includes(value)) {
      return Result.fail(new Error(`Estado de factura no válido: ${value}`));
    }
    return Result.ok(new InvoiceStatus({ value }));
  }

  getValue(): string {
    return this.props.value;
  }

  canTransitionTo(nextStatus: string): boolean {
    return InvoiceStatus.TRANSITIONS[this.props.value].includes(nextStatus);
  }

  transitionTo(nextStatus: string): Result<InvoiceStatus, Error> {
    if (!this.canTransitionTo(nextStatus)) {
      return Result.fail(
        new Error(`Transición no permitida de ${this.props.value} a ${nextStatus}`)
      );
    }
    return InvoiceStatus.create(nextStatus);
  }

  toString(): string {
    return this.getValue();
  }
}
