import { Store } from "@tauri-apps/plugin-store"
import { appLocalDataDir, join } from "@tauri-apps/api/path"

const STORE_FILENAME = "machine-agent.json"
const DEFAULT_API_BASE_URL = "https://tickets.esdrasrenan.com.br"

type MachineStoreConfig = {
  apiBaseUrl?: string
  appUrl?: string
  convexUrl?: string
}

type MachineStoreData = {
  token?: string
  config?: MachineStoreConfig
}

async function loadStore(): Promise<MachineStoreData> {
  const appData = await appLocalDataDir()
  const storePath = await join(appData, STORE_FILENAME)
  const store = await Store.load(storePath)
  const token = await store.get<string>("token")
  const config = await store.get<MachineStoreConfig>("config")
  return { token: token ?? undefined, config: config ?? undefined }
}

function normalizeUrl(value?: string | null, fallback?: string) {
  const trimmed = (value ?? fallback ?? "").trim()
  if (!trimmed) return fallback ?? ""
  return trimmed.replace(/\/+$/, "")
}

function resolveApiBaseUrl(config?: MachineStoreConfig): string {
  const fromConfig = normalizeUrl(config?.apiBaseUrl, DEFAULT_API_BASE_URL)
  return fromConfig || DEFAULT_API_BASE_URL
}

function resolveAppUrl(config?: MachineStoreConfig, apiBaseUrl?: string): string {
  const fromConfig = normalizeUrl(config?.appUrl, apiBaseUrl)
  return fromConfig || apiBaseUrl || DEFAULT_API_BASE_URL
}

export async function getMachineStoreConfig() {
  const data = await loadStore()
  if (!data.token) {
    throw new Error("Token de maquina nao encontrado no store")
  }
  const apiBaseUrl = resolveApiBaseUrl(data.config)
  const appUrl = resolveAppUrl(data.config, apiBaseUrl)
  return { token: data.token, apiBaseUrl, appUrl }
}

