import { apiGet } from './client';

export interface CallStats {
  readonly totalCalls: number;
  readonly lastSyncAt?: string;
}

export interface Call {
  readonly id: string;
  readonly deviceId: string;
  readonly externalId: string;
  readonly address: string | null;
  readonly normalizedAddress: string | null;
  readonly contactName: string | null;
  readonly direction: string | null;
  readonly callType: string | null;
  readonly answered: boolean | null;
  readonly durationSeconds: number | null;
  readonly startedAt: string | null;
  readonly serviceProvider: string | null;
  readonly syncedAt: string;
}

interface Envelope<T> {
  readonly success: boolean;
  readonly data: T;
}

function qs(params: Record<string, string | number | boolean | undefined>): string {
  const sp = new URLSearchParams();
  for (const [k, v] of Object.entries(params)) {
    if (v !== undefined && v !== '') sp.set(k, String(v));
  }
  const s = sp.toString();
  return s ? `?${s}` : '';
}

function rethrow(label: string, err: unknown): never {
  if (err instanceof Error) throw err;
  throw new Error(`${label} failed`);
}

export async function fetchCallStats(deviceId?: string): Promise<CallStats> {
  try {
    const res = await apiGet<Envelope<CallStats>>(`/my/calls/stats${deviceId ? `?deviceId=${encodeURIComponent(deviceId)}` : ''}`);
    return res.data;
  } catch (err) {
    rethrow('fetchCallStats', err);
  }
}

export interface CallFilter {
  readonly deviceId?: string;
  readonly direction?: string;
  readonly callType?: string;
  readonly limit?: number;
  readonly offset?: number;
}

export async function fetchCalls(filter: CallFilter = {}): Promise<Call[]> {
  try {
    const res = await apiGet<Envelope<{ calls: Call[] }>>(`/my/calls${qs({ ...filter })}`);
    return res.data.calls;
  } catch (err) {
    rethrow('fetchCalls', err);
  }
}
