// src/lib/api/customer-portal.ts
import { customerPortalApi } from "@/src/lib/api/customer-portal-client"

export type CustomerPortalRole = "owner" | "manager" | "viewer"
export type CustomerPortalStatus = "invited" | "active" | "suspended"

export type CustomerPortalMe = {
  user: {
    id: number
    username: string
    first_name?: string | null
    last_name?: string | null
    email?: string | null
  }

  // ✅ Réponse actuelle backend
  institute?: {
    id: number
    name: string
  } | null

  // ✅ Tolérance si plus tard tu renvoies tenant
  tenant?: {
    id: number
    name: string
  } | null

  customer: {
    id: number
    name: string
    code?: string | null
    portal_enabled: boolean
    tenant_id: number
  }

  membership: {
    id: number
    role: CustomerPortalRole
    status: CustomerPortalStatus
    is_primary_contact: boolean
  }
}

export type CaseStatus = "open" | "in_progress" | "on_hold" | "closed"
export type CasePriority = "low" | "medium" | "high" | "urgent"

export type DebtorLite = {
  id: number
  type: "individual" | "company"
  full_name: string
}

export type CaseLite = {
  id: number
  reference: string
  title: string
  status: CaseStatus
  priority: CasePriority
  currency?: string | null
  original_amount: string | number
  balance_amount: string | number
  due_date?: string | null
  opened_at?: string | null
  closed_at?: string | null
  debtor?: DebtorLite | null
  portfolio?: any | null
  metadata?: any | null
  created_source?: string | null
}

export type CaseCreate = {
  reference: string
  title: string
  status?: CaseStatus
  priority?: CasePriority
  currency?: string | null
  original_amount?: string | number
  balance_amount?: string | number
  due_date?: string | null
  debtor_id: number
  portfolio_id?: number | null

  // ✅ assignation côté client portal
  assigned_to_id?: number | null

  metadata?: any
}

export type CasePatch = Partial<Pick<CaseCreate, "title" | "priority" | "due_date" | "metadata">>

export type CaseNote = {
  id: number
  body: string
  created_at: string
  updated_at?: string | null
  author_username?: string | null
}

/**
 * Employé "local" du client (assignee).
 * Ajuste les champs si ton backend renvoie un autre shape.
 */
export type CustomerEmployee = {
  id: number
  username: string
  first_name?: string | null
  last_name?: string | null
  email?: string | null
  is_active?: boolean
}

/**
 * Helper d'affichage côté UI (facultatif)
 */
export function formatEmployeeName(e: CustomerEmployee): string {
  const full = `${e.first_name ?? ""} ${e.last_name ?? ""}`.trim()
  return full || e.username
}

/**
 * GET /customer-portal/me/
 */
export function getCustomerPortalMe(): Promise<CustomerPortalMe> {
  return customerPortalApi.request("/customer-portal/me/", { method: "GET" })
}

/**
 * GET /customer-portal/cases/?q=&status=
 */
export function listCustomerCases(params?: { q?: string; status?: CaseStatus }): Promise<CaseLite[]> {
  const qs = new URLSearchParams()

  const q = (params?.q ?? "").trim()
  if (q) qs.set("q", q)

  if (params?.status) qs.set("status", params.status)

  const url = qs.toString() ? `/customer-portal/cases/?${qs.toString()}` : "/customer-portal/cases/"
  return customerPortalApi.request(url, { method: "GET" })
}

/**
 * GET /customer-portal/cases/:id/
 */
export function getCustomerCase(id: number): Promise<any> {
  return customerPortalApi.request(`/customer-portal/cases/${id}/`, { method: "GET" })
}

/**
 * POST /customer-portal/cases/
 */
export function createCustomerCase(payload: CaseCreate): Promise<any> {
  return customerPortalApi.request("/customer-portal/cases/", {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify(payload),
  })
}

/**
 * PATCH /customer-portal/cases/:id/
 */
export function patchCustomerCase(id: number, payload: CasePatch): Promise<any> {
  return customerPortalApi.request(`/customer-portal/cases/${id}/`, {
    method: "PATCH",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify(payload),
  })
}

/**
 * GET /customer-portal/cases/:id/notes/
 */
export function listCustomerCaseNotes(caseId: number): Promise<CaseNote[]> {
  return customerPortalApi.request(`/customer-portal/cases/${caseId}/notes/`, { method: "GET" })
}

/**
 * POST /customer-portal/cases/:id/notes/
 */
export function addCustomerCaseNote(caseId: number, body: string): Promise<CaseNote> {
  return customerPortalApi.request(`/customer-portal/cases/${caseId}/notes/`, {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({ body }),
  })
}

/**
 * GET /customer-portal/employees/
 * (endpoint à confirmer côté backend; tu peux le changer ici sans toucher le front)
 */
export function listCustomerEmployees(): Promise<CustomerEmployee[]> {
  return customerPortalApi.request("/customer-portal/employees/", { method: "GET" })
}


// --- Customer Portal Debtors (Client) ---
export type CustomerPortalDebtorType = "individual" | "company"

export type CustomerPortalDebtor = {
  id: number
  type: CustomerPortalDebtorType
  full_name: string
  national_id?: string | null
  tax_id?: string | null
  phone?: string | null
  email?: string | null
  address?: string | null
  city?: string | null
  country?: string | null
  metadata?: any | null
  created_at?: string
}

export type CustomerPortalDebtorCreate = {
  type: CustomerPortalDebtorType
  full_name: string
  national_id?: string | null
  tax_id?: string | null
  phone?: string | null
  email?: string | null
  address?: string | null
  city?: string | null
  country?: string | null
  metadata?: any | null
}

export function listCustomerPortalDebtors(params?: { q?: string }): Promise<CustomerPortalDebtor[]> {
  const qs = new URLSearchParams()
  const q = (params?.q ?? "").trim()
  if (q) qs.set("q", q)

  const url = qs.toString()
    ? `/customer-portal/debtors/?${qs.toString()}`
    : "/customer-portal/debtors/"

  return customerPortalApi.request(url, { method: "GET" })
}

export function createCustomerPortalDebtor(payload: CustomerPortalDebtorCreate): Promise<CustomerPortalDebtor> {
  return customerPortalApi.request("/customer-portal/debtors/", {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify(payload),
  })
}


// --- Customer Portal Case Update + Documents ---

// Types docs
export type CaseDocumentType = "contract" | "invoice" | "letter" | "id" | "other"

export type CustomerPortalCaseDocument = {
  id: number
  title: string
  doc_type: CaseDocumentType
  file: string | null
  created_at: string
  uploaded_by?: string | null
}

export type CustomerPortalCasePatch = {
  title?: string
  priority?: "low" | "medium" | "high" | "urgent"
  due_date?: string | null
  balance_amount?: string | number
  original_amount?: string | number
  currency?: string | null

  // ✅ assignation côté client (distincte)
  customer_assigned_to_id?: number | null

  // ✅ métadata optionnel
  metadata?: any
}

export function patchCustomerCaseCustomerPortal(caseId: number, payload: CustomerPortalCasePatch): Promise<any> {
  return customerPortalApi.request(`/customer-portal/cases/${caseId}/`, {
    method: "PATCH",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify(payload),
  })
}

export function listCustomerCaseDocuments(caseId: number): Promise<CustomerPortalCaseDocument[]> {
  return customerPortalApi.request(`/customer-portal/cases/${caseId}/documents/`, {
    method: "GET",
  })
}

export function uploadCustomerCaseDocument(caseId: number, payload: { title: string; doc_type: CaseDocumentType; file: File }): Promise<CustomerPortalCaseDocument> {
  const fd = new FormData()
  fd.append("title", payload.title)
  fd.append("doc_type", payload.doc_type)
  fd.append("file", payload.file)

  return customerPortalApi.request(`/customer-portal/cases/${caseId}/documents/`, {
    method: "POST",
    body: fd as any,
  })
}


export function patchCustomerCaseDocument(
  caseId: number,
  docId: number,
  payload: { title?: string; doc_type?: CaseDocumentType; file?: File }
): Promise<CustomerPortalCaseDocument> {
  const fd = new FormData()
  if (payload.title !== undefined) fd.append("title", payload.title)
  if (payload.doc_type !== undefined) fd.append("doc_type", payload.doc_type)
  if (payload.file) fd.append("file", payload.file)

  return customerPortalApi.request(`/customer-portal/cases/${caseId}/documents/${docId}/`, {
    method: "PATCH",
    body: fd as any,
  })
}

export function deleteCustomerCaseDocument(caseId: number, docId: number): Promise<void> {
  return customerPortalApi.request(`/customer-portal/cases/${caseId}/documents/${docId}/`, {
    method: "DELETE",
  })
}


export function patchCustomerCaseNote(caseId: number, noteId: number, body: string): Promise<CaseNote> {
  return customerPortalApi.request(`/customer-portal/cases/${caseId}/notes/${noteId}/`, {
    method: "PATCH",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({ body }),
  })
}

export function deleteCustomerCaseNote(caseId: number, noteId: number): Promise<void> {
  return customerPortalApi.request(`/customer-portal/cases/${caseId}/notes/${noteId}/`, {
    method: "DELETE",
  })
}



// src/lib/api/customer-portal.ts (ajouts)
export type CaseMessageAttachment = {
  id: number
  filename?: string | null
  content_type?: string | null
  size?: number
  file: string | null
  created_at: string
}

export type CaseMessage = {
  id: number
  case_id: number
  case_reference?: string | null
  case_title?: string | null

  author: { id: number; username: string } | null
  author_side: "customer" | "tenant"

  body: string
  visibility: "shared" | "internal"
  action_required: boolean

  created_at: string
  is_read?: boolean | null

  attachments: CaseMessageAttachment[]
}

export function listCustomerInboxMessages(params?: { q?: string; unread?: boolean; action_required?: boolean }): Promise<CaseMessage[]> {
  const qs = new URLSearchParams()
  if (params?.q) qs.set("q", params.q)
  if (params?.unread) qs.set("unread", "1")
  if (params?.action_required) qs.set("action_required", "1")
  const url = qs.toString() ? `/customer-portal/messages/?${qs.toString()}` : "/customer-portal/messages/"
  return customerPortalApi.request(url, { method: "GET" })
}

export function listCustomerCaseMessages(caseId: number): Promise<CaseMessage[]> {
  return customerPortalApi.request(`/customer-portal/cases/${caseId}/messages/`, { method: "GET" })
}

export async function sendCustomerCaseMessage(caseId: number, payload: { body: string; action_required?: boolean; files?: File[] }): Promise<CaseMessage> {
  const fd = new FormData()
  fd.append("body", payload.body)
  if (payload.action_required) fd.append("action_required", "1")
  for (const f of payload.files || []) fd.append("files", f)

  return customerPortalApi.request(`/customer-portal/cases/${caseId}/messages/`, {
    method: "POST",
    body: fd as any,
  })
}

export function markCustomerMessageRead(msgId: number): Promise<any> {
  return customerPortalApi.request(`/customer-portal/messages/${msgId}/read/`, { method: "POST" })
}

export function patchCustomerCaseMessage(caseId: number, msgId: number, body: string): Promise<CaseMessage> {
  return customerPortalApi.request(`/customer-portal/cases/${caseId}/messages/${msgId}/`, {
    method: "PATCH",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({ body }),
  })
}

export function deleteCustomerCaseMessage(caseId: number, msgId: number): Promise<void> {
  return customerPortalApi.request(`/customer-portal/cases/${caseId}/messages/${msgId}/`, { method: "DELETE" })
}

// ── Typing indicator (portail client) ──────────────────────────────────────
export function getPortalTyping(caseId: number): Promise<{ typing: string[] }> {
  return customerPortalApi.request(`/customer-portal/cases/${caseId}/typing/`, { method: "GET" })
}
export function setPortalTyping(caseId: number): Promise<any> {
  return customerPortalApi.request(`/customer-portal/cases/${caseId}/typing/`, { method: "POST" })
}
export function clearPortalTyping(caseId: number): Promise<any> {
  return customerPortalApi.request(`/customer-portal/cases/${caseId}/typing/`, { method: "DELETE" })
}
