// lib/remote/remote_settings.dart
import 'package:flutter/foundation.dart';
import 'package:flutter/services.dart';
import 'package:flutter_secure_storage/flutter_secure_storage.dart';

class RemoteSettings {
  static const _storage = FlutterSecureStorage(
    aOptions: AndroidOptions(
      encryptedSharedPreferences: true,
      resetOnError: true,
    ),
  );

  static const _kEnabled   = 'remote_enabled';
  static const _kBaseUrl   = 'remote_base_url';
  static const _kIndexPath = 'remote_index_path';
  static const _kEmail     = 'remote_email';
  static const _kPassword  = 'remote_password';

  // ✅ NEW: WS URL
  static const _kWsUrl     = 'remote_ws_url';

  // ✅ remote OFF by default ALWAYS
  static const bool defaultEnabled = false;

  // ✅ in debug puoi precompilare credenziali/URL, ma NON attivare automaticamente
  static const String defaultBaseUrl   = kDebugMode ? 'https://prova.patachina.it' : '';
  static const String defaultIndexPath = kDebugMode ? 'photos/' : '';
  static const String defaultEmail     = kDebugMode ? 'fabio@gmail.com' : '';
  static const String defaultPassword  = kDebugMode ? 'master66' : '';

  /// ✅ Deriva ws/wss URL dal baseUrl in modo coerente:
  /// https://prova.patachina.it -> wss://prova-ws.patachina.it
  /// http://prova.patachina.it  -> ws://prova-ws.patachina.it
  static String deriveWsUrlFromBase(String baseUrl) {
    final uri = Uri.tryParse(baseUrl.trim());
    if (uri == null || uri.host.isEmpty) return '';

    final scheme = (uri.scheme == 'http') ? 'ws' : 'wss';
    final parts = uri.host.split('.');
    if (parts.isEmpty) return '$scheme://${uri.host}';

    // "prova" -> "prova-ws"
    parts[0] = '${parts[0]}-ws';
    return '$scheme://${parts.join('.')}';
  }

  // ✅ default WS URL in debug: derivato dal defaultBaseUrl (coerente)
  // In release: vuoto (utente lo inserisce se serve, altrimenti fallback su derivazione runtime).
  static final String defaultWsUrl = kDebugMode ? deriveWsUrlFromBase(defaultBaseUrl) : '';

  bool enabled;
  String baseUrl;
  String indexPath;
  String email;
  String password;

  /// WS URL opzionale. Se vuoto, il client può derivarlo da baseUrl (fallback).
  String wsUrl;

  RemoteSettings({
    required this.enabled,
    required this.baseUrl,
    required this.indexPath,
    required this.email,
    required this.password,
    required this.wsUrl,
  });

  static Future<String?> _readKeySafe(String key) async {
    try {
      return await _storage.read(key: key);
    } on PlatformException {
      await _storage.delete(key: key);
      return null;
    }
  }

  static String _sanitizeUrl(String s) {
    const _invisibles = r'[\u200B-\u200F\u202A-\u202E\u2060-\u2064\uFEFF]';
    final cleaned = s.replaceAll(RegExp(_invisibles), '');
    return cleaned.trim();
  }

  static Future<RemoteSettings> load() async {
    final enabledStr = await _readKeySafe(_kEnabled);
    final rawBase    = await _readKeySafe(_kBaseUrl);
    final indexPath  = await _readKeySafe(_kIndexPath) ?? defaultIndexPath;
    final email      = await _readKeySafe(_kEmail)     ?? defaultEmail;
    final password   = await _readKeySafe(_kPassword)  ?? defaultPassword;

    // ✅ NEW: wsUrl
    final rawWs      = await _readKeySafe(_kWsUrl)     ?? defaultWsUrl;

    // ✅ defaultEnabled è false sempre
    final enabled = (enabledStr ?? (defaultEnabled ? 'true' : 'false')) == 'true';
    final baseUrl = _sanitizeUrl(rawBase ?? defaultBaseUrl);
    final wsUrl   = _sanitizeUrl(rawWs);

    return RemoteSettings(
      enabled: enabled,
      baseUrl: baseUrl,
      indexPath: indexPath,
      email: email,
      password: password,
      wsUrl: wsUrl,
    );
  }

  Future<void> save() async {
    await _storage.write(key: _kEnabled,   value: enabled ? 'true' : 'false');
    await _storage.write(key: _kBaseUrl,   value: _sanitizeUrl(baseUrl));
    await _storage.write(key: _kIndexPath, value: indexPath.trim());
    await _storage.write(key: _kEmail,     value: email.trim());
    await _storage.write(key: _kPassword,  value: password);

    // ✅ NEW
    await _storage.write(key: _kWsUrl,     value: _sanitizeUrl(wsUrl));
  }

  static Future<void> debugSeedIfEmpty() async {
    if (!kDebugMode) return;

    Future<void> _seed(String key, String value) async {
      try {
        final existing = await _storage.read(key: key);
        if (existing == null) {
          await _storage.write(key: key, value: value);
        }
      } on PlatformException {
        await _storage.delete(key: key);
        await _storage.write(key: key, value: value);
      }
    }

    // ✅ anche in debug: remote parte SPENTO
    await _seed(_kEnabled, 'false');

    // ✅ precompila gli altri campi per comodità
    await _seed(_kBaseUrl,   defaultBaseUrl);
    await _seed(_kIndexPath, defaultIndexPath);
    await _seed(_kEmail,     defaultEmail);
    await _seed(_kPassword,  defaultPassword);

    // ✅ NEW: precompila wsUrl derivato dal defaultBaseUrl
    await _seed(_kWsUrl,     defaultWsUrl);
  }
}
