import settingsService from './settings.service';
import environment from '../config/environment';

export interface BookstackConfig {
  url: string;
  tokenId: string;
  tokenSecret: string;
}

export interface VikunjaConfig {
  url: string;
  apiToken: string;
}

export interface NextcloudConfig {
  url: string;
  bot_username?: string;
  bot_app_password?: string;
}

interface CacheEntry<T> {
  data: T;
  expiresAt: number;
}

const CACHE_TTL_MS = 60_000; // 60 seconds

let bookstackCache: CacheEntry<BookstackConfig> | null = null;
let vikunjaCache: CacheEntry<VikunjaConfig> | null = null;
let nextcloudCache: CacheEntry<NextcloudConfig> | null = null;

async function getDbConfig(key: string): Promise<Record<string, string>> {
  const setting = await settingsService.get(key);
  if (!setting?.value || typeof setting.value !== 'object') return {};
  return setting.value as Record<string, string>;
}

async function getBookstackConfig(): Promise<BookstackConfig> {
  if (bookstackCache && Date.now() < bookstackCache.expiresAt) {
    return bookstackCache.data;
  }

  const db = await getDbConfig('tool_config_bookstack');
  const config: BookstackConfig = {
    url: db.url || environment.bookstack.url,
    tokenId: db.tokenId || environment.bookstack.tokenId,
    tokenSecret: db.tokenSecret || environment.bookstack.tokenSecret,
  };

  bookstackCache = { data: config, expiresAt: Date.now() + CACHE_TTL_MS };
  return config;
}

async function getVikunjaConfig(): Promise<VikunjaConfig> {
  if (vikunjaCache && Date.now() < vikunjaCache.expiresAt) {
    return vikunjaCache.data;
  }

  const db = await getDbConfig('tool_config_vikunja');
  const config: VikunjaConfig = {
    url: db.url || environment.vikunja.url,
    apiToken: db.apiToken || environment.vikunja.apiToken,
  };

  vikunjaCache = { data: config, expiresAt: Date.now() + CACHE_TTL_MS };
  return config;
}

async function getNextcloudConfig(): Promise<NextcloudConfig> {
  if (nextcloudCache && Date.now() < nextcloudCache.expiresAt) {
    return nextcloudCache.data;
  }

  const db = await getDbConfig('tool_config_nextcloud');
  const config: NextcloudConfig = {
    url: db.url || environment.nextcloudUrl,
    bot_username: db.bot_username || undefined,
    bot_app_password: db.bot_app_password || undefined,
  };

  nextcloudCache = { data: config, expiresAt: Date.now() + CACHE_TTL_MS };
  return config;
}

function clearCache(): void {
  bookstackCache = null;
  vikunjaCache = null;
  nextcloudCache = null;
}

export default {
  getBookstackConfig,
  getVikunjaConfig,
  getNextcloudConfig,
  clearCache,
};
