export interface PhoneNumber {
  id: string;
  restaurantId: string;
  branchId?: string;
  number: string;
  type: 'purchased' | 'sip';
  provider?: 'twilio' | 'sip';
  sipProviderLabel?: string;
  sipConfig?: Record<string, unknown>;
  isActive: boolean;
  createdAt: string;
  updatedAt?: string;
}

export interface PhoneNumberListResponse {
  numbers: PhoneNumber[];
}

function normalize(row: Record<string, unknown>): PhoneNumber {
  return {
    id: row.id as string,
    restaurantId: (row.restaurantId ?? row.restaurant_id) as string,
    branchId: (row.branchId ?? row.branch_id) as string | undefined,
    number: row.number as string,
    type: row.type as 'purchased' | 'sip',
    provider: (row.provider as 'twilio' | 'sip' | undefined),
    sipProviderLabel: (row.sipProviderLabel ?? row.sip_provider_label) as string | undefined,
    sipConfig: (row.sipConfig ?? row.sip_config) as Record<string, unknown> | undefined,
    isActive: Boolean(row.isActive ?? row.is_active ?? true),
    createdAt: (row.createdAt ?? row.created_at) as string,
    updatedAt: (row.updatedAt ?? row.updated_at) as string | undefined,
  };
}

async function apiFetch<T>(url: string, options?: RequestInit): Promise<T> {
  const res = await fetch(url, { credentials: 'include', ...options });
  const json = (await res.json().catch(() => ({}))) as Record<string, unknown>;
  if (!res.ok) throw new Error((json.error as string) || `Request failed: ${res.status}`);
  return json as T;
}

export async function listPhoneNumbers(params: Record<string, string> = {}): Promise<PhoneNumberListResponse> {
  const qs = new URLSearchParams(params).toString();
  const data = await apiFetch<{ numbers: Record<string, unknown>[] }>(`/api/phone-numbers${qs ? '?' + qs : ''}`);
  return { numbers: data.numbers.map(normalize) };
}

export async function getPhoneNumber(id: string): Promise<{ number: PhoneNumber }> {
  const data = await apiFetch<{ number: Record<string, unknown> }>(`/api/phone-numbers/${id}`);
  return { number: normalize(data.number) };
}

export async function createPhoneNumber(body: Record<string, unknown>): Promise<{ number: PhoneNumber }> {
  const data = await apiFetch<{ number: Record<string, unknown> }>('/api/phone-numbers', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(body),
  });
  return { number: normalize(data.number) };
}

export async function updatePhoneNumber(id: string, body: Record<string, unknown>): Promise<{ number: PhoneNumber }> {
  const data = await apiFetch<{ number: Record<string, unknown> }>(`/api/phone-numbers/${id}`, {
    method: 'PATCH',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(body),
  });
  return { number: normalize(data.number) };
}

export async function deletePhoneNumber(id: string): Promise<{ success: boolean }> {
  return apiFetch<{ success: boolean }>(`/api/phone-numbers/${id}`, { method: 'DELETE' });
}
