import { baseAPI } from "@/lib/api";
import { downloadBlob } from "@/lib/export-file";
import type {
  ActivityFilters,
  ActivityFilterOptions,
  ActivityLogResponse,
} from "./activity-log-types";

type ActivitySort = { field: string; order: "asc" | "desc" };

// Filters and sort as query parameters, shared by the list and the export.
function buildActivityQuery(
  filters: ActivityFilters,
  sort?: ActivitySort,
): URLSearchParams {
  const query = new URLSearchParams();
  if (sort) {
    query.set("sortBy", sort.field);
    query.set("sortOrder", sort.order);
  }
  for (const [key, value] of Object.entries(filters)) {
    // Lists travel as one comma-separated value ("auth,users"); numbers as is.
    const text = Array.isArray(value)
      ? value.join(",")
      : typeof value === "number"
        ? String(value)
        : (value ?? "").trim();
    if (text) query.set(key, text);
  }
  return query;
}

export function getActivityLogs(
  filters: ActivityFilters,
  page: number,
  pageSize: number,
  // The column the table is sorted by; left out, the list stays newest first.
  sort?: ActivitySort,
  signal?: AbortSignal,
): Promise<ActivityLogResponse> {
  const query = buildActivityQuery(filters, sort);
  query.set("page", String(page));
  query.set("pageSize", String(pageSize));
  return baseAPI(`/activity-logs?${query}`, { signal, cache: "no-store" });
}

const API_BASE_URL =
  process.env.NEXT_PUBLIC_API_URL || "http://localhost:3001/api/v1";

// Downloads the filtered log as an Excel file (the server keeps the newest
// 5,000 rows). The export is itself recorded in the log.
export async function exportActivityLogs(
  filters: ActivityFilters,
  sort?: ActivitySort,
): Promise<void> {
  const response = await fetch(
    `${API_BASE_URL}/activity-logs/export?${buildActivityQuery(filters, sort)}`,
    { credentials: "include", cache: "no-store" },
  );
  if (!response.ok) throw new Error(`Export failed (${response.status})`);

  const filename =
    /filename="([^"]+)"/i.exec(
      response.headers.get("Content-Disposition") ?? "",
    )?.[1] ?? "activity-log.xlsx";
  downloadBlob(await response.blob(), filename);
}

export async function getActivityFilterOptions(
  signal?: AbortSignal,
): Promise<ActivityFilterOptions> {
  const response: { data: ActivityFilterOptions } = await baseAPI(
    "/activity-logs/filter-options",
    { signal, cache: "no-store" },
  );
  return response.data;
}
