// lib/core/services/database_service.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 
  // =================================================================
  
  // Save Token securely (Call this when the user logs in)
  static Future<void> saveToken(String token) async {
    try {
      final prefs = await SharedPreferences.getInstance();
      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 SharedPreferences.getInstance();
      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 SharedPreferences.getInstance();
      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 SharedPreferences.getInstance();
      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.");
  }
}
