import { TeamInfo } from "@/features/teams/types";
import { Match } from "@/features/matches/types";
import { z } from "zod";

export type TournamentFormat = "single_elim" | "double_elim" | "groups" | "swiss" | "swiss_bracket" | "round_robin";
export type TournamentPhase = "seeding" | "group_stage" | "knockout" | "completed";

export interface GroupConfig {
  num_groups: number;
  teams_per_group: number;
  advance_per_group: number;
  matches_guaranteed: number;
  seeding_method: "random" | "ranked";
}

export interface Group {
  id: string;
  tournament: string;
  name: string;
  order: number;
  teams: TeamInfo[];
  created: string;
  updated: string;
}

export interface GroupStanding {
  team: TeamInfo;
  wins: number;
  losses: number;
  cups_for: number;
  cups_against: number;
  cup_differential: number;
  rank: number;
}

export interface TournamentTeamStats {
  id: string;
  team_id: string;
  tournament_id: string;
  team_name: string;
  matches: number;
  wins: number;
  losses: number;
  total_cups_made: number;
  total_cups_against: number;
  margin_of_victory: number;
  margin_of_loss: number;
  win_percentage: number;
  avg_cups_per_match: number;
}

export interface TournamentInfo {
  id: string;
  name: string;
  location?: string;
  start_time?: string;
  end_time?: string;
  logo?: string;
  glitch_logo?: string;
  first_place?: TeamInfo;
  second_place?: TeamInfo;
  third_place?: TeamInfo;
  regional?: boolean;
}

export interface Tournament {
  id: string;
  name: string;
  location?: string;
  desc?: string;
  rules?: string;
  logo?: string;
  glitch_logo?: string;
  enroll_time?: string;
  start_time: string;
  end_time?: string;
  created: string;
  updated: string;
  teams?: TeamInfo[];
  matches?: Match[];
  first_place?: TeamInfo;
  second_place?: TeamInfo;
  third_place?: TeamInfo;
  team_stats?: TournamentTeamStats[];
  regional?: boolean;
  format?: TournamentFormat;
  group_config?: GroupConfig;
  phase?: TournamentPhase;
  groups?: Group[];
}

export const tournamentInputSchema = z.object({
  name: z.string(),
  location: z.string().optional(),
  desc: z.string().optional(),
  rules: z.string().optional(),
  logo: z.file().optional(),
  enroll_time: z.string(),
  start_time: z.string(),
  end_time: z.string().optional(),
  regional: z.boolean().optional().default(false),
  format: z.enum(["single_elim", "double_elim", "groups", "swiss", "swiss_bracket", "round_robin"]).optional(),
  phase: z.enum(["seeding", "group_stage", "knockout", "completed"]).optional(),
  group_config: z.object({
    num_groups: z.number(),
    teams_per_group: z.number(),
    advance_per_group: z.number(),
    matches_guaranteed: z.number(),
    seeding_method: z.enum(["random", "ranked"]),
  }).optional(),
});

export type TournamentInput = z.infer<typeof tournamentInputSchema>;
export type TournamentUpdateInput = Partial<TournamentInput>;
