import { AppDataSource } from '../config/database';
import { GameSetting } from '../models/GameSetting';

/**
 * GameSettingsService — resolves game constants with admin override capability.
 *
 * Pattern:
 *   const price = await GameSettingsService.get('weapon.ak47.price', WEAPONS.find(w => w.id === 'ak47')!.price);
 *
 * If a GameSetting with key 'weapon.ak47.price' exists, its JSON-parsed value is returned.
 * Otherwise, the hardcoded fallback is returned.
 *
 * Uses an in-memory cache refreshed every 60 seconds to avoid DB hits on every read.
 */
export class GameSettingsService {
  private static cache: Map<string, unknown> = new Map();
  private static lastRefresh = 0;
  private static readonly TTL_MS = 60_000; // 60 seconds

  /**
   * Refresh the in-memory cache from database.
   */
  static async refresh(): Promise<void> {
    try {
      const repo = AppDataSource.getRepository(GameSetting);
      const settings = await repo.find();
      const newCache = new Map<string, unknown>();
      for (const s of settings) {
        try {
          newCache.set(s.key, JSON.parse(s.value));
        } catch {
          newCache.set(s.key, s.value);
        }
      }
      GameSettingsService.cache = newCache;
      GameSettingsService.lastRefresh = Date.now();
    } catch {
      // DB not ready yet — keep previous cache
    }
  }

  /**
   * Ensure cache is fresh (auto-refresh if TTL expired).
   */
  private static async ensureFresh(): Promise<void> {
    if (Date.now() - GameSettingsService.lastRefresh > GameSettingsService.TTL_MS) {
      await GameSettingsService.refresh();
    }
  }

  /**
   * Get a setting value with fallback to hardcoded default.
   *
   * @param key     - Setting key (e.g. 'police.rules.points_per_crime')
   * @param fallback - Default value if no admin override exists
   * @returns The admin-overridden value or the fallback
   */
  static async get<T>(key: string, fallback: T): Promise<T> {
    await GameSettingsService.ensureFresh();
    if (GameSettingsService.cache.has(key)) {
      return GameSettingsService.cache.get(key) as T;
    }
    return fallback;
  }

  /**
   * Get multiple settings at once, returning a merged object.
   *
   * @param prefix   - Key prefix (e.g. 'police.rules')
   * @param defaults - Object with default values
   * @returns Merged object where admin overrides take precedence
   */
  static async getGroup<T extends Record<string, unknown>>(prefix: string, defaults: T): Promise<T> {
    await GameSettingsService.ensureFresh();
    const result = { ...defaults };
    for (const [key, value] of GameSettingsService.cache) {
      if (key.startsWith(`${prefix}.`)) {
        const subKey = key.slice(prefix.length + 1);
        if (subKey in result) {
          (result as Record<string, unknown>)[subKey] = value;
        }
      }
    }
    return result;
  }

  /**
   * Synchronous getter (uses cached values only, no DB hit).
   * Call refresh() at startup or periodically to keep cache populated.
   */
  static getCached<T>(key: string, fallback: T): T {
    if (GameSettingsService.cache.has(key)) {
      return GameSettingsService.cache.get(key) as T;
    }
    return fallback;
  }

  /**
   * Bulk seed: inserts default settings if they don't exist.
   * Safe to call multiple times (idempotent).
   */
  static async seedDefaults(
    entries: Array<{
      key: string;
      value: unknown;
      description?: string;
      category?: string;
      is_public?: boolean;
    }>,
  ): Promise<number> {
    const repo = AppDataSource.getRepository(GameSetting);
    let created = 0;
    for (const entry of entries) {
      const exists = await repo.findOne({ where: { key: entry.key } });
      if (!exists) {
        await repo.save(
          repo.create({
            key: entry.key,
            value: JSON.stringify(entry.value),
            description: entry.description ?? null,
            category: entry.category ?? 'general',
            is_public: entry.is_public ?? false,
          }),
        );
        created++;
      }
    }
    if (created > 0) await GameSettingsService.refresh();
    return created;
  }

  /**
   * Phase 17 (2026-05-04) — Persist une valeur (upsert atomique).
   * Utilisé notamment par le helper cron daily pour tracker le dernier
   * run par jour Paris (catch-up robuste aux PM2 reloads).
   */
  static async set(
    key: string,
    value: unknown,
    options: { description?: string; category?: string; is_public?: boolean } = {},
  ): Promise<void> {
    const repo = AppDataSource.getRepository(GameSetting);
    const existing = await repo.findOne({ where: { key } });
    if (existing) {
      existing.value = JSON.stringify(value);
      if (options.description !== undefined) existing.description = options.description;
      if (options.category !== undefined) existing.category = options.category;
      if (options.is_public !== undefined) existing.is_public = options.is_public;
      await repo.save(existing);
    } else {
      await repo.save(repo.create({
        key,
        value: JSON.stringify(value),
        description: options.description ?? null,
        category: options.category ?? 'cron-tracker',
        is_public: options.is_public ?? false,
      }));
    }
    GameSettingsService.cache.set(key, value);
  }
}
