import type { ValueObject } from '@core/shared/domain/ValueObject';

export interface PointsTableProps {
  pointsByPosition: ReadonlyMap<number, number>;
}

export class PointsTable implements ValueObject<PointsTableProps> {
  private readonly pointsByPosition: ReadonlyMap<number, number>;

  constructor(pointsByPosition: Record<number, number> | Map<number, number>) {
    if (pointsByPosition instanceof Map) {
      this.pointsByPosition = new Map(pointsByPosition);
    } else {
      this.pointsByPosition = new Map(
        Object.entries(pointsByPosition).map(([key, value]) => [Number(key), value]),
      );
    }
  }

  getPointsForPosition(position: number): number {
    if (!Number.isInteger(position) || position < 1) {
      return 0;
    }
    const value = this.pointsByPosition.get(position);
    return typeof value === 'number' ? value : 0;
  }

  get props(): PointsTableProps {
    return {
      pointsByPosition: this.pointsByPosition,
    };
  }

  equals(other: ValueObject<PointsTableProps>): boolean {
    const a = this.props.pointsByPosition;
    const b = other.props.pointsByPosition;

    if (a.size !== b.size) return false;
    for (const [key, value] of a.entries()) {
      if (b.get(key) !== value) {
        return false;
      }
    }
    return true;
  }
}