import client from "./client";

export interface DataSource {
  id: string;
  name: string;
  display_name: string;
  type: string;
  url: string | null;
  description: string | null;
  is_enabled: boolean;
  last_sync_at: string | null;
  last_sync_status: string | null;
  last_sync_stats: Record<string, unknown> | null;
  sync_frequency: string | null;
  config: Record<string, unknown> | null;
  created_at: string | null;
}

export interface SyncResult {
  message: string;
  source: string;
  stats: Record<string, unknown>;
}

export interface SyncAllResult {
  message: string;
  results: Array<{
    source: string;
    status: string;
    stats?: Record<string, unknown>;
    detail?: string;
  }>;
}

export interface DataSourceStats {
  id: string;
  name: string;
  display_name: string;
  type: string;
  is_enabled: boolean;
  last_sync_at: string | null;
  last_sync_status: string | null;
  last_sync_stats: Record<string, unknown> | null;
  total_templates: number;
  total_rules: number;
}

/** List all data sources. */
export async function getDataSources(): Promise<DataSource[]> {
  const { data } = await client.get<DataSource[]>("/data-sources");
  return data;
}

/** Update a data source (enable/disable, config). */
export async function updateDataSource(
  id: string,
  body: Partial<{ is_enabled: boolean; sync_frequency: string; config: Record<string, unknown> }>
): Promise<{ message: string; id: string }> {
  const { data } = await client.patch(`/data-sources/${id}`, body);
  return data;
}

/** Trigger sync for a specific data source. */
export async function syncDataSource(id: string): Promise<SyncResult> {
  const { data } = await client.post<SyncResult>(`/data-sources/${id}/sync`);
  return data;
}

/** Trigger sync for all enabled data sources. */
export async function syncAllDataSources(): Promise<SyncAllResult> {
  const { data } = await client.post<SyncAllResult>("/data-sources/sync-all");
  return data;
}

/** Get stats for a specific data source. */
export async function getDataSourceStats(id: string): Promise<DataSourceStats> {
  const { data } = await client.get<DataSourceStats>(`/data-sources/${id}/stats`);
  return data;
}
