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

export interface LlmConfigRow {
  id: string;
  provider: string;
  model: string;
  api_key: string;
  base_url: string;
  is_active: boolean;
  configured_by: string | null;
  created_at: string;
  updated_at: string;
}

export async function fetchActiveLlmConfig(): Promise<LlmConfigRow | null> {
  const supabase = getSupabaseClient();
  const { data, error } = await supabase
    .from('llm_config')
    .select('*')
    .eq('is_active', true)
    .order('updated_at', { ascending: false })
    .limit(1)
    .maybeSingle();

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

  return data;
}

export async function saveLlmConfig(config: {
  provider: string;
  model: string;
  api_key: string;
  base_url: string;
  configured_by?: string;
}): Promise<void> {
  const supabase = getSupabaseClient();

  // 将所有已有记录标记为非活跃
  const { error: deactivateError } = await supabase
    .from('llm_config')
    .update({ is_active: false, updated_at: new Date().toISOString() })
    .eq('is_active', true);

  if (deactivateError) {
    throw new Error(`停用旧配置失败: ${deactivateError.message}`);
  }

  // 插入新的活跃配置
  const { error: insertError } = await supabase
    .from('llm_config')
    .insert({
      provider: config.provider,
      model: config.model,
      api_key: config.api_key,
      base_url: config.base_url,
      is_active: true,
      configured_by: config.configured_by ?? null,
    });

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