import { z } from "zod";
import { TeamInfo, Team } from "../teams/types";
import { TournamentInfo } from "../tournaments/types";

export type MatchStatus = "tbd" | "ready" | "started" | "ended";
export type MatchType = "group_stage" | "knockout" | "winners" | "losers" | "bracket";

export interface Match {
  id: string;
  order: number;
  lid: number;
  reset: boolean;
  round: number;
  home_cups: number;
  away_cups: number;
  ot_count: number;
  start_time: string;
  end_time: string;
  bye: boolean;
  home_from_lid: number;
  away_from_lid: number;
  home_from_loser: boolean;
  away_from_loser: boolean;
  is_losers_bracket: boolean;
  status: MatchStatus;
  tournament: TournamentInfo;
  home?: TeamInfo | Team;
  away?: TeamInfo | Team;
  created: string;
  updated: string;
  home_seed?: number;
  away_seed?: number;
  match_type?: MatchType;
  group?: string;
  reported_home_cups?: number;
  reported_away_cups?: number;
  reported_ot_count?: number;
  reported_by_team?: string;
  reported_by_player?: string;
}

export const matchInputSchema = z.object({
  order: z.number().int().min(1).optional(),
  lid: z.number().int().min(1),
  reset: z.boolean().optional().default(false),
  round: z.number().int().min(1),
  home_cups: z.number().int().min(0).optional().default(0),
  away_cups: z.number().int().min(0).optional().default(0),
  ot_count: z.number().int().min(0).optional().default(0),
  start_time: z.iso.datetime().optional(),
  end_time: z.iso.datetime().optional(),
  bye: z.boolean().optional().default(false),
  home_from_lid: z.number().int().min(1).optional(),
  away_from_lid: z.number().int().min(1).optional(),
  home_from_loser: z.boolean().optional().default(false),
  away_from_loser: z.boolean().optional().default(false),
  is_losers_bracket: z.boolean().optional().default(false),
  status: z.enum(["tbd", "ready", "started", "ended"]).optional().default("tbd"),
  tournament: z.string().min(1),
  home: z.string().min(1).nullable().optional(),
  away: z.string().min(1).nullable().optional(),
  home_seed: z.number().int().min(1).optional(),
  away_seed: z.number().int().min(1).optional(),
  match_type: z.enum(["group_stage", "knockout", "winners", "losers", "bracket"]).optional(),
  group: z.string().optional(),
  reported_home_cups: z.number().int().min(0).nullable().optional(),
  reported_away_cups: z.number().int().min(0).nullable().optional(),
  reported_ot_count: z.number().int().min(0).nullable().optional(),
  reported_by_team: z.string().nullable().optional(),
  reported_by_player: z.string().nullable().optional(),
});

export type MatchInput = z.infer<typeof matchInputSchema>;
export type MatchUpdateInput = Partial<MatchInput>;
