/**
 * Inquiries inbox (API reference: "How the inquiries inbox works", "Inquiries").
 *
 * Every website form (Contact, Home, Media & Insights, product "Request a quote") posts to
 * POST /public/inquiries; the admin reads them here. Statuses: new → in_progress (automatic
 * on the first note) → closed; spam for junk. Nothing is emailed yet.
 */
import { ApiError, api, apiPaged, authedFetch } from "./api";

export type InquiryStatus = "new" | "in_progress" | "closed" | "spam";
export type InquirySource = "contact" | "home" | "media-insights" | "product";
type Who = { id: string; email: string } | null;

/** A row of GET /admin/inquiries (no message or notes). */
export type InquiryRow = {
  id: string;
  status: InquiryStatus;
  source: InquirySource;
  inquiryType: { key: string; label: string } | null;
  name: string;
  email: string;
  phone: string | null;
  company: string | null;
  hasMessage: boolean;
  notesCount: number;
  product?: { id: string; slug: string; name: string; sku: string | null } | null;
  createdAt: string;
  updatedAt: string;
};

export type InquiryNote = { id: string; text: string; by: Who; at: string };

/** GET /admin/inquiries/:id */
export type Inquiry = Omit<InquiryRow, "hasMessage" | "notesCount"> & {
  message: string | null;
  meeting: { date: string | null; time: string | null } | null;
  quantity: { value: number; unit: string } | null;
  language: string | null;
  region: string | null;
  country: string | null;
  pageUrl: string | null;
  section: string | null;
  statusChangedBy: Who;
  statusChangedAt: string | null;
  notes: InquiryNote[];
};

export type InquirySummary = {
  total: number;
  byStatus: Partial<Record<InquiryStatus, number>>;
  bySource: Partial<Record<InquirySource, number>>;
};

export type InquiryQuery = {
  page: number;
  limit: number;
  status: "" | InquiryStatus;
  source: "" | InquirySource;
  search: string;
  /** YYYY-MM-DD */
  from: string;
  to: string;
};

export const STATUSES: { value: InquiryStatus; label: string; tone: "b" | "a" | "g" | "n" | "r" }[] = [
  { value: "new", label: "New", tone: "b" },
  { value: "in_progress", label: "In progress", tone: "a" },
  { value: "closed", label: "Closed", tone: "g" },
  { value: "spam", label: "Spam", tone: "n" },
];
export const statusOf = (s: InquiryStatus) => STATUSES.find((x) => x.value === s) ?? STATUSES[0];

/** Inbox tabs, in order ("" = all). */
export const SOURCES: { value: "" | InquirySource; label: string }[] = [
  { value: "", label: "All" },
  { value: "contact", label: "Contact" },
  { value: "home", label: "Home" },
  { value: "media-insights", label: "Media" },
  { value: "product", label: "Product quotes" },
];
export const SOURCE_LABEL: Record<InquirySource, string> = { contact: "Contact page", home: "Home page", "media-insights": "Media & Insights", product: "Product quote" };

/** Filters shared by the list and the CSV export. */
const filters = (q: Omit<InquiryQuery, "page" | "limit">) => ({
  status: q.status || undefined,
  source: q.source || undefined,
  search: q.search.trim() || undefined,
  from: q.from || undefined,
  to: q.to || undefined,
});

export const inquiriesApi = {
  list: (q: InquiryQuery) => apiPaged<InquiryRow>("/admin/inquiries", { page: q.page, limit: q.limit, ...filters(q) }),
  summary: () => api<InquirySummary>("/admin/inquiries/summary"),
  get: (id: string) => api<Inquiry>(`/admin/inquiries/${id}`),
  setStatus: (id: string, status: InquiryStatus) => api<Inquiry>(`/admin/inquiries/${id}/status`, { method: "PATCH", body: { status } }),
  addNote: (id: string, text: string) => api<Inquiry>(`/admin/inquiries/${id}/notes`, { method: "POST", body: { text } }),
  remove: (id: string) => api<void>(`/admin/inquiries/${id}`, { method: "DELETE" }),
};

/** Downloads inquiries.csv with the list's filters (newest first, at most 5000 rows). */
export async function exportInquiries(q: Omit<InquiryQuery, "page" | "limit">): Promise<void> {
  const params = new URLSearchParams();
  for (const [k, v] of Object.entries(filters(q))) if (v) params.set(k, v);
  const res = await authedFetch(`/admin/inquiries/export${params.size ? `?${params}` : ""}`, { method: "GET" });
  if (!res.ok) {
    const body = await res.json().catch(() => null);
    throw new ApiError(res.status, body?.message ?? `Export failed (${res.status})`, Array.isArray(body?.errors) ? body.errors : []);
  }
  const blob = await res.blob();
  const url = URL.createObjectURL(blob);
  const a = Object.assign(document.createElement("a"), { href: url, download: "inquiries.csv" });
  document.body.append(a);
  a.click();
  a.remove();
  setTimeout(() => URL.revokeObjectURL(url), 1000);
}
