import api from './api';

export type CompetitionAlias = {
  code: string;
  alias: string;
  original_name?: string;
  display_order?: number;
};

// Public: fetch all aliases
export async function getCompetitionAliasesPublic(): Promise<CompetitionAlias[]> {
  const res = await api.get<CompetitionAlias[] | { data: CompetitionAlias[] }>(
    '/competition-aliases'
  );
  return Array.isArray(res.data) ? res.data : (res.data as any).data;
}

// Admin: list all aliases
export async function getCompetitionAliasesAdmin(): Promise<CompetitionAlias[]> {
  const res = await api.get<CompetitionAlias[] | { data: CompetitionAlias[] }>(
    '/admin/competition-aliases'
  );
  return Array.isArray(res.data) ? res.data : (res.data as any).data;
}

// Admin: upsert alias by code
export async function upsertCompetitionAlias(code: string, payload: { alias: string; original_name?: string; display_order?: number }): Promise<CompetitionAlias> {
  const res = await api.put<CompetitionAlias | { data: CompetitionAlias }>(
    `/admin/competition-aliases/${encodeURIComponent(code)}`,
    payload
  );
  return (res.data as any).code ? (res.data as any) : (res.data as any).data;
}

// Admin: delete alias by code
export async function deleteCompetitionAlias(code: string): Promise<{ ok: boolean } | void> {
  const res = await api.delete<{ ok: boolean } | any>(
    `/admin/competition-aliases/${encodeURIComponent(code)}`
  );
  return (res.data && typeof res.data.ok !== 'undefined') ? res.data : undefined;
}

// Admin: reorder competition aliases
export async function reorderCompetitionAliases(items: Array<{ code: string; display_order: number }>): Promise<{ ok: boolean; updated: number }> {
  const res = await api.post<{ ok: boolean; updated: number }>(
    '/admin/competition-aliases/reorder',
    { items }
  );
  return res.data;
}
