import "server-only"

import { desc, eq } from "drizzle-orm"

import { db } from "@/shared/db"
import { aiProviders } from "@/shared/db/schema"

import { decryptAiApiKey } from "./api-key-crypto"

export type AiProviderConfig = {
  apiKey: string
  baseUrl?: string
  model: string
}

export const getAiProviderConfig = async (providerId?: string): Promise<AiProviderConfig> => {
  if (providerId) {
    const [selected] = await db
      .select({
        apiKeyEncrypted: aiProviders.apiKeyEncrypted,
        baseUrl: aiProviders.baseUrl,
        model: aiProviders.model,
      })
      .from(aiProviders)
      .where(eq(aiProviders.id, providerId))
      .limit(1)
    if (!selected) throw new Error("AI provider not configured")
    return {
      apiKey: decryptAiApiKey(selected.apiKeyEncrypted),
      baseUrl: selected.baseUrl ?? undefined,
      model: selected.model,
    }
  }

  const [active] = await db
    .select({
      apiKeyEncrypted: aiProviders.apiKeyEncrypted,
      baseUrl: aiProviders.baseUrl,
      model: aiProviders.model,
    })
    .from(aiProviders)
    .where(eq(aiProviders.isDefault, true))
    .orderBy(desc(aiProviders.updatedAt))
    .limit(1)
  if (active) {
    return {
      apiKey: decryptAiApiKey(active.apiKeyEncrypted),
      baseUrl: active.baseUrl ?? undefined,
      model: active.model,
    }
  }

  const [fallback] = await db
    .select({
      apiKeyEncrypted: aiProviders.apiKeyEncrypted,
      baseUrl: aiProviders.baseUrl,
      model: aiProviders.model,
    })
    .from(aiProviders)
    .orderBy(desc(aiProviders.updatedAt))
    .limit(1)
  if (!fallback) throw new Error("AI provider not configured")

  return {
    apiKey: decryptAiApiKey(fallback.apiKeyEncrypted),
    baseUrl: fallback.baseUrl ?? undefined,
    model: fallback.model,
  }
}
