import { API_BASE, qs } from "./auth";
import type {
  AdminProductRow,
  PageResponse,
  PlatformDto,
  ProductStatus,
  ProductVisibility,
} from "./types";

import type { CaliberDto } from "./types";

export async function fetchAdminRoles(params: Record<string, any>) {
  const queryString = qs(params);
  const res = await fetch(
    `/api/admin/products/roles${queryString ? `?${queryString}` : ''}`,
    {
      credentials: "include",
      cache: "no-store",
    }
  );
  if (!res.ok) throw new Error(`Failed to load roles (${res.status}): ${await res.text()}`);
  return (await res.json()) as string[];
}

// Facet/filtering can still use distinct values seen on products (optional)
export async function fetchProductCaliberFacet(params: Record<string, any>) {
  const queryString = qs(params);
  const res = await fetch(
    `/api/admin/products/calibers${queryString ? `?${queryString}` : ''}`,
    {
      credentials: "include",
      cache: "no-store",
    }
  );
  if (!res.ok)
    throw new Error(
      `Failed to load caliber facet (${res.status}): ${await res.text()}`
    );
  return (await res.json()) as string[];
}

export async function fetchAdminProducts(params: Record<string, any>) {
  const queryString = qs(params);
  const res = await fetch(
    `/api/admin/products${queryString ? `?${queryString}` : ''}`,
    {
      credentials: "include",
      cache: "no-store",
    }
  );
  if (!res.ok) throw new Error(`Failed to load admin products (${res.status}): ${await res.text()}`);
  return (await res.json()) as PageResponse<AdminProductRow>;
}

export async function fetchPlatforms() {
  const res = await fetch(`${API_BASE}/api/platforms`, {
    method: "GET",
    headers: { Accept: "application/json" },
    cache: "no-store",
  });

  if (!res.ok) throw new Error(`Failed to load platforms (${res.status}): ${await res.text()}`);
  const all = (await res.json()) as PlatformDto[];
  return all.filter((p) => (p as any).is_active ?? (p as any).isActive);
}

export async function bulkUpdate(
  productIds: number[],
  set: Partial<{
    visibility: ProductVisibility;
    status: ProductStatus;
    builderEligible: boolean;
    adminLocked: boolean;
    adminNote: string;
    platform: string;
    platformLocked: boolean;
    caliber: string;
    caliberGroup: string;
    caliberLocked: boolean;
    forceCaliberUpdate: boolean;
    partRole: string;
    partRoleLocked: boolean;
    classificationReason: "Admin bulk override";
  }>
) {
  const res = await fetch(`/api/admin/products/bulk`, {
    method: "PATCH",
    credentials: "include",
    headers: {
      "Content-Type": "application/json",
    },
    body: JSON.stringify({ productIds, ...set }),
  });

  if (!res.ok) throw new Error(`Bulk update failed (${res.status}): ${await res.text()}`);

  return (await res.json()) as { updatedCount: number; skippedLockedCount: number };
}


export async function fetchAdminCalibers(params: Record<string, any>) {
  const queryString = qs(params);
  const res = await fetch(
    `/api/admin/calibers${queryString ? `?${queryString}` : ''}`,
    {
      credentials: "include",
      cache: "no-store",
    }
  );
  if (!res.ok) {
    throw new Error(`Failed to load calibers (${res.status}): ${await res.text()}`);
  }
  return (await res.json()) as CaliberDto[];
}