import { getVelocityToken } from './velocityPlatformClient';
import type {
  CommsThread,
  CommsSettings,
  CommsProviderTestResult,
  SendMessagePayload,
  CommsThreadListResponse,
  CommsMessageListResponse,
  ThreadLinkPayload,
} from '@/types/commsTypes';

const API_BASE = import.meta.env.VITE_API_BASE_URL || '';

async function commsFetch(path: string, options?: RequestInit) {
  const token = getVelocityToken();
  const res = await fetch(`${API_BASE}${path}`, {
    ...options,
    headers: {
      'Content-Type': 'application/json',
      ...(token ? { Authorization: `Bearer ${token}` } : {}),
      ...options?.headers,
    },
  });
  if (!res.ok) {
    const err = await res.json().catch(() => ({}));
    throw new Error(err.detail || `HTTP ${res.status}`);
  }
  return res.json();
}

function toQuery(params?: Record<string, string | number | undefined>) {
  const query = new URLSearchParams();
  Object.entries(params ?? {}).forEach(([key, value]) => {
    if (value !== undefined && value !== '') query.set(key, String(value));
  });
  const serialized = query.toString();
  return serialized ? `?${serialized}` : '';
}

export const fetchCommsThreads = (params?: { status?: string; search?: string; limit?: number; offset?: number }) =>
  commsFetch(`/api/comms/threads${toQuery(params)}`) as Promise<CommsThreadListResponse>;

export const fetchCommsThread = (threadId: string) =>
  commsFetch(`/api/comms/threads/${threadId}`) as Promise<CommsThread>;

export const fetchCommsMessages = (threadId: string, params?: { limit?: number; offset?: number }) =>
  commsFetch(`/api/comms/threads/${threadId}/messages${toQuery(params)}`) as Promise<CommsMessageListResponse>;

export const sendCommsMessage = (threadId: string, payload: SendMessagePayload) =>
  commsFetch(`/api/comms/threads/${threadId}/messages`, {
    method: 'POST',
    body: JSON.stringify(payload),
  });

export const linkCommsThreadToPerson = (threadId: string, payload: ThreadLinkPayload) =>
  commsFetch(`/api/comms/threads/${threadId}/link-person`, {
    method: 'POST',
    body: JSON.stringify(payload),
  });

export const addCommsThreadNote = (threadId: string, body: { content: string }) =>
  commsFetch(`/api/comms/threads/${threadId}/notes`, {
    method: 'POST',
    body: JSON.stringify(body),
  });

export const addCommsThreadTask = (threadId: string, body: { title: string; dueAt?: string }) =>
  commsFetch(`/api/comms/threads/${threadId}/tasks`, {
    method: 'POST',
    body: JSON.stringify(body),
  });

export const fetchCommsSettings = () =>
  commsFetch(`/api/comms/settings`) as Promise<CommsSettings>;

export const updateCommsSettings = (payload: Partial<CommsSettings>) =>
  commsFetch(`/api/comms/settings`, {
    method: 'PATCH',
    body: JSON.stringify(payload),
  });

export const testCommsProviderConnection = () =>
  commsFetch(`/api/comms/provider/test`, { method: 'POST' }) as Promise<CommsProviderTestResult>;

export const transcribeCommsRecording = (callId: string) =>
  commsFetch(`/api/comms/recordings/transcribe`, {
    method: 'POST',
    body: JSON.stringify({ callId }),
  });
