import { fetchWithAuth } from "./client";

function buildQuery(params: Record<string, string | number | boolean | undefined>): string {
  const qs = Object.entries(params)
    .filter(([, v]) => v !== undefined)
    .map(([k, v]) => `${encodeURIComponent(k)}=${encodeURIComponent(String(v))}`)
    .join("&");
  return qs ? `?${qs}` : "";
}

export interface SchemaAdviseRequest {
  brand_id: string;
  target_url?: string;
  focus_dimensions?: string[];
}

export interface SchemaSuggestion {
  id: string;
  brand_id: string;
  schema_type: string;
  target_url: string | null;
  json_ld: Record<string, unknown>;
  validation_status: string | null;
  validation_errors: string[] | null;
  priority: number | null;
  status: string;
  created_at: string;
  updated_at: string;
}

export interface SchemaSuggestionList {
  suggestions: SchemaSuggestion[];
  total: number;
}

export interface SchemaSuggestionResponse extends SchemaSuggestion {}

export const schemaAdvisorApi = {
  advise: (token: string, data: SchemaAdviseRequest) =>
    fetchWithAuth("/api/v1/schema/advise", {
      method: "POST",
      body: JSON.stringify(data),
    }, token) as Promise<SchemaSuggestionList>,

  getBrandSuggestions: (
    token: string,
    brandId: string,
    params?: { status?: string; schema_type?: string; skip?: number; limit?: number }
  ) =>
    fetchWithAuth(
      `/api/v1/schema/brand/${brandId}${buildQuery(params || {})}`,
      {},
      token
    ) as Promise<SchemaSuggestionList>,

  getSuggestion: (token: string, suggestionId: string) =>
    fetchWithAuth(`/api/v1/schema/${suggestionId}`, {}, token) as Promise<SchemaSuggestionResponse>,

  updateStatus: (token: string, suggestionId: string, status: string) =>
    fetchWithAuth(`/api/v1/schema/${suggestionId}/status`, {
      method: "PUT",
      body: JSON.stringify({ status }),
    }, token) as Promise<SchemaSuggestionResponse>,
};
