// lib/core/services/database_service.dart
import 'dart:io';
import 'package:flutter/foundation.dart';
import 'package:isar/isar.dart';
import 'package:path_provider/path_provider.dart';
import 'package:shared_preferences/shared_preferences.dart'; // <-- ADDED FOR TOKEN CACHING
import '../models/user.dart';

class DatabaseService {
  static late Isar isar;

  // 1. Initialize the Isar database (Called in main.dart)
  static Future<void> init() async {
    final dir = await getApplicationDocumentsDirectory();
    isar = await Isar.open(
      [LocalUserSchema],
      directory: dir.path,
    );
  }

  // 2. Save or Update a User Profile
  static Future<void> saveUserLocally(LocalUser user) async {
    await isar.writeTxn(() async {
      await isar.localUsers.put(user);
    });
  }

  // --- ADDED: Alias method to fully support saveLocalUser calls ---
  static Future<void> saveLocalUser(LocalUser user) async {
    await saveUserLocally(user);
  }

  // 3. Retrieve the Current Local User
  static Future<LocalUser?> getLocalUser() async {
    // Safety check to ensure the instance is open before querying
    if (Isar.getInstance() == null) {
      return null; 
    }
    // Search the database and return the first user profile it finds
    return await isar.localUsers.where().findFirst();
  }

  // =================================================================
  // NEW: TOKEN MANAGEMENT (WITH SELF-HEALING RECOVERY)
  // =================================================================
  
  static Future<SharedPreferences> _getSafePrefs() async {
    try {
      return await SharedPreferences.getInstance();
    } catch (e) {
      if (e is FormatException || e.toString().contains('FormatException')) {
        debugPrint('⚠️ Corrupted SharedPreferences detected. Self-healing...');
        try {
          if (!kIsWeb && Platform.isWindows) {
            final appData = Platform.environment['APPDATA'];
            if (appData != null) {
              final candidates = [
                File('$appData/com.example/skill_end/shared_preferences.json'),
                File('$appData/skill_end/shared_preferences.json'),
              ];
              for (final f in candidates) {
                if (f.existsSync()) {
                  f.writeAsStringSync('{}');
                  debugPrint('✅ Repaired preferences file: ${f.path}');
                }
              }
            }
          }
          final dir = await getApplicationSupportDirectory();
          final f = File('${dir.path}/shared_preferences.json');
          if (f.existsSync()) {
            f.writeAsStringSync('{}');
          }
          return await SharedPreferences.getInstance();
        } catch (inner) {
          debugPrint('❌ Auto-recovery failed: $inner');
        }
      }
      rethrow;
    }
  }

  // Save Token securely (Call this when the user logs in)
  static Future<void> saveToken(String token) async {
    try {
      final prefs = await _getSafePrefs();
      await prefs.setString('token', token);
    } catch (e) {
      print('Error saving token: $e');
    }
  }

  // Retrieve Token for API Calls and Main.dart Routing
  static Future<String> getToken() async {
    try {
      final prefs = await _getSafePrefs();
      return prefs.getString('token') ?? ''; 
    } catch (e) {
      print('Error fetching token: $e');
      return '';
    }
  }

  /// Remove only the saved API session token while preserving offline data.
  static Future<void> clearToken() async {
    try {
      final prefs = await _getSafePrefs();
      await prefs.remove('token');
    } catch (e) {
      print('Error clearing token: $e');
    }
  }

  // ------------------------------------------------------------------
  // DATABASE CLEANING METHODS 
  // ------------------------------------------------------------------

  // 4. Wipe the Entire Database & Token (Best for full Logout or App Reset)
  static Future<void> cleanEntireDatabase() async {
    await isar.writeTxn(() async {
      await isar.clear(); // This deletes EVERYTHING in all Isar collections
    });
    
    // Destroy the API token during logout to prevent ghost sessions and 401 loops
    try {
      final prefs = await _getSafePrefs();
      await prefs.remove('token');
    } catch (e) {
      print('Error clearing token: $e');
    }

    print("🧹 Isar Database and API Token completely wiped.");
  }

  // 5. Wipe Specific Collection 
  static Future<void> cleanUserCollection() async {
    await isar.writeTxn(() async {
      await isar.localUsers.clear(); 
    });
    print("🧹 LocalUser collection cleared.");
  }
}
