import type { AuthPlatform } from "./auth";

const API_BASE = import.meta.env.VITE_API_URL ?? "/api";

export type SearchCategory = "clients" | "documents" | "suppliers" | "questions" | "activity";

export interface SearchHit {
  id: string;
  category: SearchCategory;
  title: string;
  subtitle?: string | null;
  meta?: string | null;
  status?: string | null;
  reference_type: string;
  reference_id: string;
  score: number;
}

export interface SearchResponse {
  query: string;
  total: number;
  items: SearchHit[];
  categories: Partial<Record<SearchCategory, SearchHit[]>>;
}

function identityParams(platform: AuthPlatform, email: string, clientId?: string) {
  const params = new URLSearchParams({
    platform,
    email: email.trim().toLowerCase(),
  });
  if (platform === "client" && clientId) {
    params.set("client_id", clientId);
  }
  return params;
}

export async function searchApi(
  platform: AuthPlatform,
  email: string,
  q: string,
  opts?: {
    clientId?: string;
    mode?: "autocomplete" | "full";
    category?: SearchCategory | "all";
    limit?: number;
    signal?: AbortSignal;
  },
): Promise<SearchResponse> {
  const params = identityParams(platform, email, opts?.clientId);
  params.set("q", q);
  params.set("mode", opts?.mode ?? "autocomplete");
  if (opts?.category) params.set("category", opts.category);
  if (opts?.limit != null) params.set("limit", String(opts.limit));

  const response = await fetch(`${API_BASE}/search?${params.toString()}`, {
    signal: opts?.signal,
  });
  if (!response.ok) {
    throw new Error(await response.text());
  }
  return (await response.json()) as SearchResponse;
}

export function searchNavigation(
  platform: AuthPlatform,
  hit: SearchHit,
): { to: string; params?: Record<string, string>; search?: Record<string, string> } {
  if (platform === "firm") {
    switch (hit.reference_type) {
      case "invoice":
        return { to: "/invoices/$id", params: { id: hit.reference_id } };
      case "client":
        return { to: "/clients", search: { highlight: hit.reference_id } };
      case "supplier":
        return { to: "/inbox", search: { q: hit.reference_id } };
      case "query":
        return { to: "/queries/$id", params: { id: hit.reference_id } };
      case "activity":
        if (hit.reference_id && hit.reference_id.startsWith("INV")) {
          return { to: "/invoices/$id", params: { id: hit.reference_id } };
        }
        return { to: "/activity" };
      default:
        return { to: "/search", search: { q: hit.title } };
    }
  }

  switch (hit.reference_type) {
    case "invoice":
      return { to: "/documents/$id", params: { id: hit.reference_id } };
    case "query":
      return { to: "/queries/$id", params: { id: hit.reference_id } };
    case "activity":
      if (hit.reference_id && hit.reference_id.startsWith("INV")) {
        return { to: "/documents/$id", params: { id: hit.reference_id } };
      }
      return { to: "/" };
    default:
      return { to: "/search", search: { q: hit.title } };
  }
}

export const FIRM_SEARCH_FILTERS: { key: SearchCategory | "all"; label: string }[] = [
  { key: "all", label: "All" },
  { key: "clients", label: "Clients" },
  { key: "documents", label: "Documents" },
  { key: "suppliers", label: "Suppliers" },
  { key: "questions", label: "Questions" },
  { key: "activity", label: "Activity" },
];

export const CLIENT_SEARCH_FILTERS: { key: SearchCategory | "all"; label: string }[] = [
  { key: "all", label: "All" },
  { key: "documents", label: "Documents" },
  { key: "questions", label: "Questions" },
  { key: "activity", label: "Activity" },
];

export function categoryLabel(cat: SearchCategory): string {
  switch (cat) {
    case "clients":
      return "Clients";
    case "documents":
      return "Documents";
    case "suppliers":
      return "Suppliers";
    case "questions":
      return "Questions";
    case "activity":
      return "Activity";
  }
}
