import { getSupabaseClient } from '@/lib/supabase';

export interface LlmProviderConfigRow {
  id: string;
  provider_key: string;
  api_key: string;
  base_url: string;
  is_active: boolean;
  configured_by: string | null;
  created_at: string;
  updated_at: string;
}

export interface LlmStageRouteRow {
  stage: string;
  provider_key: string;
  model: string;
  updated_by: string | null;
  created_at: string;
  updated_at: string;
}

export async function fetchLlmProviderConfigs(): Promise<LlmProviderConfigRow[]> {
  const supabase = getSupabaseClient();
  const { data, error } = await supabase
    .from('llm_provider_configs')
    .select('*')
    .order('provider_key', { ascending: true });

  if (error) {
    throw new Error(`获取 LLM Provider 配置失败: ${error.message}`);
  }

  return data ?? [];
}

export async function fetchLlmStageRoutes(): Promise<LlmStageRouteRow[]> {
  const supabase = getSupabaseClient();
  const { data, error } = await supabase
    .from('llm_stage_routes')
    .select('*')
    .order('stage', { ascending: true });

  if (error) {
    throw new Error(`获取 LLM 阶段路由失败: ${error.message}`);
  }

  return data ?? [];
}

export async function saveLlmProviderConfigs(configs: Array<{
  provider_key: string;
  api_key: string;
  base_url: string;
  is_active: boolean;
  configured_by?: string;
}>): Promise<void> {
  const supabase = getSupabaseClient();
  const now = new Date().toISOString();
  const rows = configs.map((config) => ({
    provider_key: config.provider_key,
    api_key: config.api_key,
    base_url: config.base_url,
    is_active: config.is_active,
    configured_by: config.configured_by ?? null,
    updated_at: now,
  }));

  const { error } = await supabase
    .from('llm_provider_configs')
    .upsert(rows, { onConflict: 'provider_key' });

  if (error) {
    throw new Error(`保存 LLM Provider 配置失败: ${error.message}`);
  }
}

export async function saveLlmStageRoutes(routes: Array<{
  stage: string;
  provider_key: string;
  model: string;
  updated_by?: string;
}>): Promise<void> {
  const supabase = getSupabaseClient();
  const now = new Date().toISOString();
  const rows = routes.map((route) => ({
    stage: route.stage,
    provider_key: route.provider_key,
    model: route.model,
    updated_by: route.updated_by ?? null,
    updated_at: now,
  }));

  const { error } = await supabase
    .from('llm_stage_routes')
    .upsert(rows, { onConflict: 'stage' });

  if (error) {
    throw new Error(`保存 LLM 阶段路由失败: ${error.message}`);
  }
}
