

export type TruckStatus = "EN_RUTA" | "DETENIDO" | "FINALIZADO" | "FALLA";

export interface GpsUpdateDto {
  truckId: string;
  routeId: string;
  lat: number;
  lng: number;
  speed: number;
  status: TruckStatus;
  positionId: number | undefined;
  timestamp: string | undefined;
}

const VALID_STATUSES: TruckStatus[] = ["EN_RUTA", "DETENIDO", "FINALIZADO", "FALLA"];

export class GpsUpdateDtoValidator {
  static validate(data: unknown): GpsUpdateDto {
    if (typeof data !== "object" || data === null) {
      throw new Error("Invalid GPS update payload");
    }

    const obj = data as Record<string, unknown>;

    const truckId = obj.truckId;
    if (typeof truckId !== "string" && typeof truckId !== "number") {
      throw new Error("truckId is required");
    }

    if (typeof obj.routeId !== "string" || obj.routeId.trim().length === 0) {
      throw new Error("routeId is required");
    }

    if (typeof obj.lat !== "number" || Number.isNaN(obj.lat)) {
      throw new Error("lat is required and must be numeric");
    }

    if (typeof obj.lng !== "number" || Number.isNaN(obj.lng)) {
      throw new Error("lng is required and must be numeric");
    }

    const speed =
      typeof obj.speed === "number" && !Number.isNaN(obj.speed) ? obj.speed : 0;

    const status: TruckStatus =
      typeof obj.status === "string" && VALID_STATUSES.includes(obj.status as TruckStatus)
        ? (obj.status as TruckStatus)
        : "EN_RUTA";

    const positionId =
      typeof obj.positionId === "number" ? obj.positionId : undefined;

    const timestamp =
      typeof obj.timestamp === "string" ? obj.timestamp : undefined;

    return {
      truckId: String(truckId),
      routeId: obj.routeId.trim(),
      lat: obj.lat,
      lng: obj.lng,
      speed,
      status,
      positionId,
      timestamp,
    };
  }
}