import { z } from 'zod';
import { GAME_TYPE } from '../Game.const';
import { gameKartStateSchema, gameSchema, kartRankingItemSchema } from '../Game.schema';

// --- Helper Schemas ---

export const kartProgressSchema = z.object({
  checkpointId: z.string(),
  checkpointProgress: z.number(),
  timestampISO: z.object({
    origin: z.string(),
    server: z.string(),
  }),
  lap: z.number(),
  totalProgress: z.number(),
});

export const lapTimeSchema = z.object({
  lap: z.number(),
  timeInSeconds: z.number(),
  completedAt: z.string(),
  completedAtCheckpointId: z.string(),
  completedAtCheckpointProgress: z.number(),
});

export const raceKartStateSchema = gameKartStateSchema.extend({
  currentLap: z.number(),
});

export const raceRankingItemSchema = kartRankingItemSchema.extend({
  progress: z.number(),
  lapsCompleted: z.number(),
});

export const rankingWithKartsAndLapTimesSchema = raceRankingItemSchema.extend({
  lapTimes: z.array(lapTimeSchema),
  fastestLap: lapTimeSchema.nullable(),
});

// --- Main Race Schema ---

export const raceSchema = gameSchema.extend({
  type: z.literal(GAME_TYPE.Race),
  laps: z.number(),
  kartsState: z.record(z.string(), raceKartStateSchema),
  kartsProgress: z.record(z.string(), z.array(kartProgressSchema)),
  gameRanking: z.array(raceRankingItemSchema),
});

export const raceWithDetailedRankingSchema = raceSchema.omit({ kartsProgress: true }).extend({
  gameRanking: z.array(rankingWithKartsAndLapTimesSchema),
});

export const kartLapTimesSchema = z.object({
  kartGuid: z.string(),
  lapTimes: z.array(lapTimeSchema),
});
