import api from './api';

export interface Player {
  id: number;
  first_name: string;
  last_name: string;
  date_of_birth?: string; // ISO date string
  position?: string;
  jersey_number?: number;
  team_id?: number;
  nationality?: string;
  height?: number;
  weight?: number;
  image_url?: string;
  is_active: boolean;
  created_at?: string;
  email?: string;
  phone?: string;
}

// Normalize backend payloads where gorm.Model serializes as `ID` rather than `id`.
// Also keep only the fields we use.
function normalize(p: any): Player {
  if (!p) return p as any;
  const id = p.id ?? p.ID;
  return {
    id: typeof id === 'string' ? Number(id) : id,
    first_name: p.first_name ?? p.FirstName ?? '',
    last_name: p.last_name ?? p.LastName ?? '',
    date_of_birth: p.date_of_birth ?? p.DateOfBirth ?? undefined,
    position: p.position ?? p.Position ?? undefined,
    jersey_number: p.jersey_number ?? p.JerseyNumber ?? undefined,
    team_id: p.team_id ?? p.TeamID ?? undefined,
    nationality: p.nationality ?? p.Nationality ?? undefined,
    height: p.height ?? p.Height ?? undefined,
    weight: p.weight ?? p.Weight ?? undefined,
    image_url: p.image_url ?? p.ImageURL ?? undefined,
    is_active: Boolean(p.is_active ?? p.IsActive ?? true),
    created_at: p.created_at ?? p.CreatedAt ?? undefined,
    email: p.email ?? p.Email ?? undefined,
    phone: p.phone ?? p.Phone ?? undefined,
  } as Player;
}

export async function getPlayers(): Promise<Player[]> {
  const res = await api.get<any[] | { data?: any[]; items?: any[] }>('/players');
  const raw = Array.isArray(res.data)
    ? res.data
    : ((res.data as any).data || (res.data as any).items);
  return (raw || []).map(normalize);
}

export async function createPlayer(payload: Partial<Player>) {
  // Admin endpoint requires auth token via api interceptor
  const res = await api.post<any>('/players', payload);
  return normalize(res.data);
}

export async function updatePlayer(id: number | string, payload: Partial<Player>) {
  const res = await api.put<any>(`/players/${id}`, payload);
  return normalize(res.data);
}

export async function deletePlayer(id: number | string) {
  const res = await api.delete<{ zprava: string }>(`/players/${id}`);
  return res.data;
}
