import 'package:appwrite/models.dart';
import 'package:appwrite/appwrite.dart';

import '../configs/environment.dart';

class AppwriteService {
  static final String endpoint = Environment.appwritePublicEndpoint;
  static final String projectId = Environment.appwriteProjectId;
  static final String realtimeCollectionId =
      Environment.appwriteRealtimeCollectionId;
  static final String databaseId = Environment.appwriteDatabaseId;
  static final String userEmail = Environment.appwriteUserEMail;
  static final String passwd = Environment.appwritePasswd;

  final Client _client = Client().setProject(projectId).setEndpoint(endpoint);

  late final Databases _databases;
  late final Account _account;
  bool _sessionActive = false;

  AppwriteService._internal() {
    _databases = Databases(_client);
    _account = Account(_client);
  }

  static final AppwriteService _instance = AppwriteService._internal();

  /// Singleton instance getter
  factory AppwriteService() => _instance;

  /// Login mit Email/Passwort. Erstellt nur eine neue Session wenn noch keine aktiv ist.
  Future<bool> login() async {
    if (_sessionActive) return true;
    try {
      await _account.getSession(sessionId: 'current');
      _sessionActive = true;
      return true;
    } catch (_) {
      // Keine aktive Session – neu einloggen
    }
    try {
      await _account.createEmailPasswordSession(
        email: userEmail,
        password: passwd,
      );
      _sessionActive = true;
      print('Appwrite Login erfolgreich');
      return true;
    } catch (e) {
      print('Fehler beim Login: $e');
      return false;
    }
  }

  // Get List<Document> from Realtime Collection
  Future<List<Document>> getDocumentsFromCollection() async {
    try {
      final documents = await _databases.listDocuments(
        databaseId: databaseId,
        collectionId: realtimeCollectionId,
        queries: [Query.orderAsc('name'), Query.orderDesc('date')],
      );
      return documents.documents;
    } catch (e) {
      print('Fehler beim Abrufen der Dokumente: $e');
      return [];
    }
  }

  // Get Document per Id from Realtime Collection
  Future<Document?> getDocumentById(String documentId) async {
    try {
      final document = await _databases.getDocument(
        databaseId: databaseId,
        collectionId: realtimeCollectionId,
        documentId: documentId,
      );
      return document;
    } catch (e) {
      print('Fehler beim Abrufen des Dokuments: $e');
      return null;
    }
  }

  // Save a new document to Realtime Collection
  Future<bool> createDocumentInCollection(Map<String, dynamic> data) async {
    try {
      await _databases.createDocument(
        databaseId: databaseId,
        collectionId: realtimeCollectionId,
        documentId: ID.unique(),
        data: data,
      );
      print('Dokument erfolgreich erstellt');
      return true;
    } catch (e) {
      print('Fehler beim Erstellen des Dokuments: $e');
      return false;
    }
  }

  // Update an existing document in Realtime Collection
  Future<bool> updateDocumentInCollection(
    String documentId,
    Map<String, dynamic> data,
  ) async {
    try {
      await _databases.updateDocument(
        databaseId: databaseId,
        collectionId: realtimeCollectionId,
        documentId: documentId,
        data: data,
      );
      print('Dokument erfolgreich aktualisiert');
      return true;
    } catch (e) {
      print('Fehler beim Aktualisieren des Dokuments: $e');
      return false;
    }
  }

  // Delete a document from Realtime Collection
  Future<bool> deleteDocumentFromCollection(String documentId) async {
    try {
      await _databases.deleteDocument(
        databaseId: databaseId,
        collectionId: realtimeCollectionId,
        documentId: documentId,
      );
      print('Dokument erfolgreich gelöscht');
      return true;
    } catch (e) {
      print('Fehler beim Löschen des Dokuments: $e');
      return false;
    }
  }
}
