import { apiGet, apiPost } from './client';
import type { Conversation, Message } from '@/types';

export async function fetchMailConversations(deviceId?: string): Promise<Conversation[]> {
  try {
    const qs = deviceId ? `?deviceId=${encodeURIComponent(deviceId)}` : '';
    return await apiGet<Conversation[]>(`/my/mail/conversations${qs}`);
  } catch (err) {
    throw err instanceof Error ? err : new Error('fetchMailConversations failed');
  }
}

export async function fetchMailThread(conversationId: string, limit = 100, since?: string): Promise<Message[]> {
  try {
    const params = new URLSearchParams({ limit: String(limit) });
    if (since) params.set('since', since);
    return await apiGet<Message[]>(`/my/mail/conversations/${encodeURIComponent(conversationId)}/messages?${params}`);
  } catch (err) {
    throw err instanceof Error ? err : new Error('fetchMailThread failed');
  }
}

export interface SendMailInput {
  readonly to: string;
  readonly cc?: readonly string[];
  readonly bcc?: readonly string[];
  readonly subject: string;
  readonly body: string;
  readonly isHtml?: boolean;
}

export interface SendMailResult {
  readonly sendQueueId: string;
}

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

export async function sendMail(input: SendMailInput, deviceId: string): Promise<SendMailResult> {
  try {
    const res = await apiPost<Envelope<SendMailResult>>(
      `/my/mail/send?deviceId=${encodeURIComponent(deviceId)}`,
      input,
    );
    return res.data;
  } catch (err) {
    throw err instanceof Error ? err : new Error('sendMail failed');
  }
}
