// src/lib/api/portfolios.ts
import { api } from "@/src/lib/api/client"

export type PortfolioPriority = "low" | "medium" | "high"

export type Portfolio = {
  id: number
  name: string
  code?: string | null
  category?: string | null
  priority: PortfolioPriority
  default_currency?: string | null
  description?: string | null
  internal_notes?: string | null

  owner?: number | null
  owner_username?: string | null

  is_active: boolean
  archived_at?: string | null

  created_by?: number | null
  updated_by?: number | null
  created_at: string
  updated_at: string

  // KPIs optionnels renvoyés par le backend
  cases_count?: number | null
  cases_total?: number | null
  open_cases_count?: number | null
  cases_open?: number | null
  overdue_cases_count?: number | null
  cases_overdue?: number | null
  balance_total?: string | number | null
}

export type PortfolioCreate = {
  name: string
  code?: string | null
  category?: string | null
  priority?: PortfolioPriority
  default_currency?: string | null
  description?: string | null
  internal_notes?: string | null
  owner?: number | null
  is_active?: boolean
  archived_at?: string | null
}

export type PortfolioUpdate = Partial<PortfolioCreate>

export function listPortfolios(params?: {
  q?: string
  is_active?: boolean
  is_archived?: boolean
  priority?: PortfolioPriority
}): Promise<Portfolio[]> {
  const qs = new URLSearchParams()

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

  // ✅ DRF attend "true"/"false" (ton backend check ("true","false"))
  if (typeof params?.is_active === "boolean") qs.set("is_active", params.is_active ? "true" : "false")
  if (typeof params?.is_archived === "boolean") qs.set("is_archived", params.is_archived ? "true" : "false")

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

  const url = qs.toString() ? `/portfolios/?${qs.toString()}` : "/portfolios/"
  // ✅ on passe explicitement method GET (robuste selon ton api.request)
  return api.request(url, { method: "GET" })
}

export function createPortfolio(payload: PortfolioCreate): Promise<Portfolio> {
  return api.request("/portfolios/", {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify(payload),
  })
}

export function updatePortfolio(id: number, payload: PortfolioUpdate): Promise<Portfolio> {
  return api.request(`/portfolios/${id}/`, {
    method: "PATCH",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify(payload),
  })
}

export function deletePortfolio(id: number): Promise<void> {
  return api.request(`/portfolios/${id}/`, { method: "DELETE" })
}
