export interface ConversationMessage {
  id: string;
  sender: string;
  text: string;
  time: string;
  confidence?: number;
}

export interface Conversation {
  id: string;
  restaurantId: string;
  branchId?: string;
  customerId?: string;
  customerName: string;
  customerPhone?: string;
  customerEmail?: string;
  channel: string;
  status: string;
  topic?: string;
  assignedAgent?: string;
  aiConfidence?: number;
  unreadCount: number;
  messages: ConversationMessage[];
  createdAt: string;
  updatedAt: string;
}

export interface ConversationListResponse {
  conversations: Conversation[];
  total: number;
  page: number;
  limit: number;
  pages: number;
}

function normalizeMessage(raw: Record<string, unknown>): ConversationMessage {
  return {
    id: String(raw.id ?? ''),
    sender: String(raw.sender ?? raw.role ?? ''),
    text: String(raw.text ?? raw.content ?? ''),
    time: String(raw.time ?? raw.created_at ?? raw.createdAt ?? raw.timestamp ?? ''),
    confidence: raw.confidence != null ? Number(raw.confidence) : undefined,
  };
}

export function normalizeConversation(raw: Record<string, unknown>): Conversation {
  const rawMsgs = Array.isArray(raw.messages) ? raw.messages : [];
  return {
    id: String(raw.id ?? ''),
    restaurantId: String(raw.restaurant_id ?? raw.restaurantId ?? ''),
    branchId: raw.branch_id != null ? String(raw.branch_id) : (raw.branchId != null ? String(raw.branchId) : undefined),
    customerId: raw.customer_id != null ? String(raw.customer_id) : (raw.customerId != null ? String(raw.customerId) : undefined),
    customerName: String(raw.customer_name ?? raw.customerName ?? 'Unknown'),
    customerPhone: raw.customer_phone != null ? String(raw.customer_phone) : (raw.customerPhone != null ? String(raw.customerPhone) : undefined),
    customerEmail: raw.customer_email != null ? String(raw.customer_email) : (raw.customerEmail != null ? String(raw.customerEmail) : undefined),
    channel: String(raw.channel ?? 'chat'),
    status: String(raw.status ?? 'ai'),
    topic: raw.topic != null ? String(raw.topic) : undefined,
    assignedAgent: raw.assigned_agent != null ? String(raw.assigned_agent) : (raw.assignedAgent != null ? String(raw.assignedAgent) : undefined),
    aiConfidence: raw.ai_confidence != null ? Number(raw.ai_confidence) : (raw.aiConfidence != null ? Number(raw.aiConfidence) : undefined),
    unreadCount: Number(raw.unread_count ?? raw.unreadCount ?? 0),
    messages: rawMsgs.map((m: Record<string, unknown>) => normalizeMessage(m)),
    createdAt: String(raw.created_at ?? raw.createdAt ?? ''),
    updatedAt: String(raw.updated_at ?? raw.updatedAt ?? ''),
  };
}

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 listConversations(params: Record<string, string> = {}): Promise<ConversationListResponse> {
  const qs = new URLSearchParams(params).toString();
  const raw = await apiFetch<{ conversations: Record<string, unknown>[]; total: number; page: number; limit: number; pages: number }>(`/api/conversations${qs ? '?' + qs : ''}`);
  return {
    conversations: (raw.conversations ?? []).map(normalizeConversation),
    total: raw.total,
    page: raw.page,
    limit: raw.limit,
    pages: raw.pages,
  };
}

export async function getConversation(id: string): Promise<{ conversation: Conversation }> {
  const raw = await apiFetch<{ conversation: Record<string, unknown> }>(`/api/conversations/${id}`);
  return { conversation: normalizeConversation(raw.conversation) };
}

export async function createConversation(body: Record<string, unknown>): Promise<{ conversation: Conversation }> {
  const raw = await apiFetch<{ conversation: Record<string, unknown> }>('/api/conversations', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(body),
  });
  return { conversation: normalizeConversation(raw.conversation) };
}

export async function updateConversation(id: string, body: Record<string, unknown>): Promise<{ conversation: Conversation }> {
  const raw = await apiFetch<{ conversation: Record<string, unknown> }>(`/api/conversations/${id}`, {
    method: 'PATCH',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(body),
  });
  return { conversation: normalizeConversation(raw.conversation) };
}

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

export async function bulkUpdateConversations(ids: string[], body: Record<string, unknown>): Promise<{ updated: number }> {
  return apiFetch<{ updated: number }>('/api/conversations', {
    method: 'PATCH',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ ids, ...body }),
  });
}

export async function bulkDeleteConversations(ids: string[]): Promise<{ success: boolean }> {
  return apiFetch<{ success: boolean }>('/api/conversations', {
    method: 'DELETE',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ ids }),
  });
}
