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

export type SupportCategory = "access" | "cases" | "documents" | "payments" | "other"
export type SupportPriority = "normal" | "urgent"
export type SupportStatus = "open" | "in_progress" | "waiting_customer" | "resolved" | "closed"

export type SupportTicket = {
  id: number
  subject: string
  category: SupportCategory
  priority: SupportPriority
  status: SupportStatus
  case_id?: number | null
  last_activity_at: string
  created_at: string
  updated_at: string
  last_message?: {
    id: number
    side: "customer" | "tenant" | "platform"
    author_username?: string | null
    created_at: string
    body_preview: string
  } | null
}

export type TicketAttachment = {
  id: number
  filename?: string | null
  content_type?: string | null
  size?: number | null
  file: string | null
  created_at: string
}

export type TicketMessage = {
  id: number
  ticket: number
  side: "customer" | "tenant" | "platform"
  body: string
  created_at: string
  author?: { id: number; username: string; first_name?: string | null; last_name?: string | null; email?: string | null } | null
  attachments: TicketAttachment[]
}

export function listSupportTickets(params?: { q?: string; status?: SupportStatus }): Promise<SupportTicket[]> {
  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/support/tickets/?${qs.toString()}`
    : "/customer-portal/support/tickets/"
  return customerPortalApi.request(url, { method: "GET" })
}

export function getSupportTicket(id: number): Promise<SupportTicket> {
  return customerPortalApi.request(`/customer-portal/support/tickets/${id}/`, { method: "GET" })
}

export async function createSupportTicket(payload: {
  subject: string
  body: string
  category?: SupportCategory
  priority?: SupportPriority
  case_id?: number | null
  files?: File[]
}): Promise<SupportTicket> {
  const fd = new FormData()
  fd.set("subject", payload.subject)
  fd.set("body", payload.body)
  if (payload.category) fd.set("category", payload.category)
  if (payload.priority) fd.set("priority", payload.priority)
  if (payload.case_id != null) fd.set("case_id", String(payload.case_id))
  for (const f of payload.files || []) fd.append("files", f)

  return customerPortalApi.request("/customer-portal/support/tickets/", {
    method: "POST",
    body: fd,
  })
}

export function listTicketMessages(ticketId: number): Promise<TicketMessage[]> {
  return customerPortalApi.request(`/customer-portal/support/tickets/${ticketId}/messages/`, { method: "GET" })
}

export async function addTicketMessage(ticketId: number, payload: { body: string; files?: File[] }): Promise<TicketMessage> {
  const fd = new FormData()
  fd.set("body", payload.body)
  for (const f of payload.files || []) fd.append("files", f)

  return customerPortalApi.request(`/customer-portal/support/tickets/${ticketId}/messages/`, {
    method: "POST",
    body: fd,
  })
}

export function patchTicket(ticketId: number, payload: { status?: "open" | "closed" }): Promise<SupportTicket> {
  return customerPortalApi.request(`/customer-portal/support/tickets/${ticketId}/`, {
    method: "PATCH",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify(payload),
  })
}
