import axios from 'axios';
import { getHttpClient, apiErrorMessage } from './http';
import { getAppConfig } from './storage';

export interface ThreadMessageRow {
  id: number;
  sender: string;
  body: string;
  channel?: string | null;
  createdAt?: string | null;
  whatsappStatus?: string | null;
}

export interface ThreadConversation {
  id: number;
  clientId?: number | null;
  messages: ThreadMessageRow[];
}

export interface WhatsappSessionInfo {
  ready: boolean;
  userName?: string | null;
}

export interface WhatsappSyncResult {
  imported: number;
  hint?: string | null;
  thread?: ThreadConversation;
}

function isMissingEndpoint(err: unknown): boolean {
  return axios.isAxiosError(err) && (err.response?.status === 404 || err.response?.status === 405);
}

function mapMessage(raw: Record<string, unknown>): ThreadMessageRow {
  return {
    id: Number(raw.id ?? 0),
    sender: String(raw.sender ?? ''),
    body: String(raw.body ?? ''),
    channel: raw.channel != null ? String(raw.channel) : null,
    createdAt: raw.createdAt != null ? String(raw.createdAt) : null,
    whatsappStatus: raw.whatsappStatus != null ? String(raw.whatsappStatus) : null,
  };
}

function mapThreadConversation(raw: Record<string, unknown>): ThreadConversation {
  const messages = Array.isArray(raw.messages)
    ? (raw.messages as Record<string, unknown>[]).map(mapMessage)
    : [];

  return {
    id: Number(raw.id),
    clientId: raw.clientId != null ? Number(raw.clientId) : raw.client_id != null ? Number(raw.client_id) : null,
    messages,
  };
}

export async function supportsWhatsappSync(): Promise<boolean> {
  const config = await getAppConfig();
  return config.mode === 'new';
}

export async function findThreadIdForClient(clientId: number): Promise<number | null> {
  const { client } = await getHttpClient();
  try {
    const { data } = await client.get<{ data: { id: number }[] }>('/mobile/threads', {
      params: { client_id: clientId, per_page: 1 },
    });
    return data.data?.[0]?.id ?? null;
  } catch {
    // Legacy / missing join / 404 — WhatsApp can still send locally without a thread
    return null;
  }
}

export async function fetchThreadConversation(threadId: number): Promise<ThreadConversation> {
  const { client, config } = await getHttpClient();

  try {
    const { data } = await client.get<{ data: Record<string, unknown> }>(`/mobile/threads/${threadId}`);
    return mapThreadConversation(data.data ?? {});
  } catch (err) {
    if (config.mode === 'new' && isMissingEndpoint(err)) {
      const { data } = await client.get<{ data: Record<string, unknown> }>(`/threads/${threadId}`);
      return mapThreadConversation(data.data ?? {});
    }
    throw new Error(apiErrorMessage(err));
  }
}

export async function fetchThreadWhatsappSession(threadId: number): Promise<WhatsappSessionInfo> {
  const { client, config } = await getHttpClient();
  if (config.mode !== 'new') {
    return { ready: false };
  }

  try {
    const { data } = await client.get<{ data: WhatsappSessionInfo }>(`/mobile/threads/${threadId}/whatsapp-session`);
    return data.data ?? { ready: false };
  } catch (err) {
    if (isMissingEndpoint(err)) {
      const { data } = await client.get<{ data: WhatsappSessionInfo }>(`/threads/${threadId}/whatsapp-session`);
      return data.data ?? { ready: false };
    }
    return { ready: false };
  }
}

export async function syncThreadWhatsapp(
  threadId: number,
  opts?: { fullHistory?: boolean },
): Promise<WhatsappSyncResult> {
  const { client, config } = await getHttpClient();
  if (config.mode !== 'new') {
    return { imported: 0, hint: 'sync_legacy_unavailable' };
  }

  try {
    const { data } = await client.post<{ data: WhatsappSyncResult & { thread?: Record<string, unknown> } }>(
      `/mobile/threads/${threadId}/messages/sync-whatsapp`,
      null,
      { params: opts?.fullHistory ? { full_history: 1 } : undefined },
    );
    const payload = data.data ?? { imported: 0 };
    return {
      imported: payload.imported ?? 0,
      hint: payload.hint ?? null,
      thread: payload.thread ? mapThreadConversation(payload.thread) : undefined,
    };
  } catch (err) {
    if (isMissingEndpoint(err)) {
      const { data } = await client.post<{ data: WhatsappSyncResult & { thread?: Record<string, unknown> } }>(
        `/threads/${threadId}/messages/sync-whatsapp`,
        null,
        { params: opts?.fullHistory ? { full_history: 1 } : undefined },
      );
      const payload = data.data ?? { imported: 0 };
      return {
        imported: payload.imported ?? 0,
        hint: payload.hint ?? null,
        thread: payload.thread ? mapThreadConversation(payload.thread) : undefined,
      };
    }
    throw new Error(apiErrorMessage(err));
  }
}

export { apiErrorMessage };
