import apiClient from './client'

// ─── Firme ────────────────────────────────────────────────────────────────────

export interface SignatureResponse {
  id: string
  tenant_id: string
  name: string
  description: string | null
  body_html: string | null
  body_text: string | null
  created_by: string | null
  created_at: string
  updated_at: string
}

export interface SignatureCreate {
  name: string
  description?: string | null
  body_html?: string | null
  body_text?: string | null
}

export interface SignatureUpdate {
  name?: string
  description?: string | null
  body_html?: string | null
  body_text?: string | null
}

// ─── Assegnazioni ─────────────────────────────────────────────────────────────

export type SignatureContext = 'reply' | 'compose' | 'both'

export interface SignatureAssignmentResponse {
  id: string
  tenant_id: string
  signature_id: string
  mailbox_id: string | null
  virtual_box_id: string | null
  context: SignatureContext
  created_at: string
  signature_name: string | null
}

export interface SignatureAssignmentCreate {
  signature_id: string
  mailbox_id?: string | null
  virtual_box_id?: string | null
  context: SignatureContext
}

// ─── API client ───────────────────────────────────────────────────────────────

export const signaturesApi = {
  // Firme
  list: (q?: string) =>
    apiClient
      .get<{ items: SignatureResponse[]; total: number }>('/signatures', {
        params: { q },
      })
      .then((r) => r.data),

  get: (id: string) =>
    apiClient.get<SignatureResponse>(`/signatures/${id}`).then((r) => r.data),

  create: (data: SignatureCreate) =>
    apiClient.post<SignatureResponse>('/signatures', data).then((r) => r.data),

  update: (id: string, data: SignatureUpdate) =>
    apiClient.put<SignatureResponse>(`/signatures/${id}`, data).then((r) => r.data),

  delete: (id: string) =>
    apiClient.delete(`/signatures/${id}`).then((r) => r.data),

  // Assegnazioni
  listAssignments: (params?: { mailbox_id?: string; virtual_box_id?: string }) =>
    apiClient
      .get<{ items: SignatureAssignmentResponse[]; total: number }>('/signatures/assignments', {
        params,
      })
      .then((r) => r.data),

  createAssignment: (data: SignatureAssignmentCreate) =>
    apiClient
      .post<SignatureAssignmentResponse>('/signatures/assignments', data)
      .then((r) => r.data),

  deleteAssignment: (id: string) =>
    apiClient.delete(`/signatures/assignments/${id}`).then((r) => r.data),

  // Risolve la firma per una casella/vbox nel contesto dato (usato dal ComposeModal)
  resolve: (params: { context: 'reply' | 'compose'; mailbox_id?: string; virtual_box_id?: string }) =>
    apiClient
      .get<SignatureResponse | null>('/signatures/resolve', { params })
      .then((r) => r.data),
}
