import { fetchApi } from "@/lib/api/http";
import type {
  PagedClientsResponse,
  ClientsPagedParams,
  ClientsPagedResponse,
  ClientScope,
  ClientSignedDocUrl,
  ClientSource,
} from "@/lib/api/types/clients.types";

// SAME base as companies — the /api prefix is what was missing
export const CLIENTS_API_BASE_URL =
  process.env.NEXT_PUBLIC_API_URL ?? "http://localhost:3007/api";

export interface ClientsQueryParams {
  page?: number;
  limit?: number;
  source?: string;
  search?: string;
}

export async function getClientsPagedAll(
  params: ClientsQueryParams = {},
): Promise<PagedClientsResponse> {
  const { page = 1, limit = 50, source = "All", search = "" } = params;
  const query = new URLSearchParams();
  query.set("page", String(page));
  query.set("limit", String(limit));
  query.set("source", source);
  if (search) query.set("search", search);

  return fetchApi<PagedClientsResponse>(
    `${CLIENTS_API_BASE_URL}/clients/paged-all?${query.toString()}`,
  );
}

// 🔹 NEW: fetch full client details from old CRM (auto-fill in audit request form)
export interface ClientDetailsResponse {
  client_ref_id: number;
  client_group: string;
  company_source: string;
  company_name: string;
  auditee_name: string;
  auditee_designation: string;
  auditee_contact: string;
  auditee_email: string;
  auditees: { name: string; designation: string }[];
  location: string;
  standard_name: string;
  accreditation: string;
  meta: Record<string, string | null>;
}

export async function getClientDetails(
  id: number,
  source: "QRS" | "TQS",
  type: "Client" | "Surveillance",
): Promise<ClientDetailsResponse> {
  const query = new URLSearchParams();
  query.set("source", source);
  query.set("type", type);

  return fetchApi<ClientDetailsResponse>(
    `${CLIENTS_API_BASE_URL}/clients/details/${id}?${query.toString()}`,
  );
}

// ═══════════════════════════════════════════════════════════════════════
// 🔹 ADDED — Clients module (list page). Everything above is untouched.
// Same CLIENTS_API_BASE_URL, so nothing about your existing calls changes.
// ═══════════════════════════════════════════════════════════════════════

function qs(params: Record<string, string | number | undefined>): string {
  const sp = new URLSearchParams();
  for (const [k, v] of Object.entries(params)) {
    if (v === undefined || v === "" || v === null) continue;
    sp.append(k, String(v));
  }
  const s = sp.toString();
  return s ? `?${s}` : "";
}

/** Clients + surveillance in one merged, owner-scoped list (typed rows). */
export async function getClientsPaged(
  params: ClientsPagedParams = {},
): Promise<ClientsPagedResponse> {
  const {
    page = 1,
    limit = 10,
    source = "All",
    type = "All",
    search,
  } = params;

  return fetchApi<ClientsPagedResponse>(
    `${CLIENTS_API_BASE_URL}/clients/paged-all${qs({ page, limit, source, type, search })}`,
  );
}

/** Clients only. */
export async function getClientsOnlyPaged(
  params: ClientsPagedParams = {},
): Promise<ClientsPagedResponse> {
  const { page = 1, limit = 10, source = "All", search } = params;
  return fetchApi<ClientsPagedResponse>(
    `${CLIENTS_API_BASE_URL}/clients/paged-clients${qs({ page, limit, source, search })}`,
  );
}

/** Surveillance only. */
export async function getSurvesPaged(
  params: ClientsPagedParams = {},
): Promise<ClientsPagedResponse> {
  const { page = 1, limit = 10, source = "All", search } = params;
  return fetchApi<ClientsPagedResponse>(
    `${CLIENTS_API_BASE_URL}/clients/paged-surves${qs({ page, limit, source, search })}`,
  );
}

/**
 * Diagnostic — returns the legacy QRS/TQS ids this user maps to.
 * If both come back null, the user's email has no match in the legacy DBs
 * and their list will legitimately be empty.
 */
export async function getClientScope(): Promise<ClientScope> {
  return fetchApi<ClientScope>(`${CLIENTS_API_BASE_URL}/clients/my-scope`);
}

// ═══════════════════════════════════════════════════════════════════════
// 🔹 ADDED — Signed document (same flow as audit-report file/url|stream)
// ═══════════════════════════════════════════════════════════════════════

/**
 * STRATEGY A — ask Nest for the public URL, then window.open(url).
 * 404s when nothing is uploaded; 403s if the row belongs to another user.
 */
export async function getClientSignedDocUrl(
  id: number,
  source: ClientSource,
): Promise<ClientSignedDocUrl> {
  return fetchApi<ClientSignedDocUrl>(
    `${CLIENTS_API_BASE_URL}/clients/signed-doc/url${qs({ id, source })}`,
  );
}

/**
 * STRATEGY B — direct link to the Nest stream endpoint (bytes proxied
 * from disk), if you'd rather not expose the legacy public URLs.
 */
export function clientSignedDocStreamUrl(
  id: number,
  source: ClientSource,
): string {
  return `${CLIENTS_API_BASE_URL}/clients/signed-doc/stream${qs({ id, source })}`;
}
/** 🔒 Server-side exact name match — returns 0 or 1 client only. */
export async function searchClientExact(
  name: string,
  source: 'QRS' | 'TQS',
): Promise<PagedClientsResponse> {
  const query = new URLSearchParams();
  query.set('name', name);
  query.set('source', source);
  return fetchApi<PagedClientsResponse>(
    `${CLIENTS_API_BASE_URL}/clients/search-exact?${query.toString()}`,
  );
}