import type { Session, User, DebriefRow, Participation, UserGlobalStats, SessionDebriefRow } from '../types';

// In dev mode, the Vite proxy forwards /proserve to localhost
// In production (built), the API is on the same host
const API_BASE = '/proserve';

async function callApi<T>(endpoint: string, params: Record<string, string | number> = {}): Promise<T> {
  const formData = new URLSearchParams();
  for (const [key, value] of Object.entries(params)) {
    formData.append(key, String(value));
  }

  const response = await fetch(`${API_BASE}/${endpoint}`, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded',
    },
    body: formData.toString(),
  });

  if (!response.ok) {
    throw new Error(`API error: ${response.status} ${response.statusText}`);
  }

  return response.json();
}

// Sessions
export async function getAllSessions(typeId = -1): Promise<Session[]> {
  const data = await callApi<{ status: boolean; stats: Session[] }>('lists/all_sessions.php', { typeId });
  return data.stats || [];
}

export async function getSessionsForUser(userId: number, typeId = -1): Promise<Session[]> {
  const data = await callApi<{ status: boolean; stats: Session[] }>('lists/sessions_for_user.php', { userId, typeId });
  return data.stats || [];
}

export async function getSession(sessionId: number): Promise<Session | null> {
  const data = await callApi<{ status: boolean; session: Session }>('session/get.php', { sessionId });
  return data.session || null;
}

// Users
export async function getAllUsers(): Promise<User[]> {
  const data = await callApi<{ status: boolean; stats: User[] }>('lists/all_users.php');
  return data.stats || [];
}

export async function getUser(userId: number): Promise<User | null> {
  const data = await callApi<{ status: boolean; user: User }>('user/get.php', { userId });
  return data.user || null;
}

export async function getUsersInSession(sessionId: number): Promise<User[]> {
  const data = await callApi<{ status: boolean; stats: User[] }>('lists/users_in_session.php', { sessionId });
  return data.stats || [];
}

// Stats & Debrief
export async function getDebrief(sessionId: number, userId = -1): Promise<DebriefRow[]> {
  const data = await callApi<{ status: boolean; stats: DebriefRow[] }>('stats/get.php', {
    sessionId,
    userId,
  });
  return data.stats || [];
}

export async function getSessionStats(sessionId: number, userId = -1, sessionType = -1): Promise<SessionDebriefRow[]> {
  const params: Record<string, string | number> = { sessionId };
  if (userId > 0) params.userId = userId;
  if (sessionType >= 0) params.sessionType = sessionType;
  const data = await callApi<{ status: boolean; stats: SessionDebriefRow[] }>('stats/get.php', params);
  return data.stats || [];
}

export async function getObjectives(sessionId: number, userId = -1): Promise<Participation | null> {
  const params: Record<string, string | number> = { sessionId };
  if (userId > 0) params.userId = userId;
  const data = await callApi<{ status: boolean; participation: Participation }>('session/getobjectives.php', params);
  return data.participation || null;
}

export async function getUserHistory(userId: number, quickMode = true): Promise<UserGlobalStats | null> {
  const data = await callApi<{ status: boolean; stats: UserGlobalStats[] }>('stats/userhistory.php', {
    userId,
    sessionId: -1,
    quickMode: quickMode ? 'true' : 'false',
  });
  return data.stats?.[0] || null;
}
