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

class AppwriteService {
  static final String endpoint = Environment.appwritePublicEndpoint;
  static final String projectId = Environment.appwriteProjectId;
  static final String projectName = Environment.appwriteProjectName;
  static final String realtimeCollectionId =
      Environment.appwriteRealtimeCollectionId;
  static final String databaseId = Environment.appwriteDatabaseId;

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

  // ignore: unused_field
  late final Account _account;
  // ignore: unused_field
  late final Databases _databases;

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

  static final AppwriteService _instance = AppwriteService._internal();

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

  // register new user with userName, e-Mail and password
  Future<bool> register(String userName, String email, String password) async {
    try {
      final user = await _account.create(
        userId: ID.unique(),
        email: email,
        password: password,
        name: userName,
      );
      print('Registrierung erfolgreich: ${user.$id}');
      return true;
    } catch (e) {
      print('Registrierung fehlgeschlagen: $e');
      return false;
    }
  }

  // login with e-Mail and password
  Future<bool> login(String email, String password) async {
    await logout();
    try {
      final session = await _account.createEmailPasswordSession(
        email: email,
        password: password,
      );
      print('Login erfolgreich: ${session.$id}');
      return true;
    } catch (e) {
      print('Login fehlgeschlagen: $e');
      return false;
    }
  }

  // logout current user
  Future<bool> logout() async {
    try {
      await _account.deleteSession(sessionId: 'current');
      print('Logout erfolgreich');
      return true;
    } catch (e) {
      print('Logout fehlgeschlagen: $e');
      return false;
    }
  }

  //Get current user ID
  Future<String?> getCurrentUserId() async {
    try {
      final user = await _account.get();
      return user.$id;
    } catch (e) {
      print('Fehler beim Abrufen der Benutzer-ID: $e');
      return null;
    }
  }

  // Get List<Document> from Realtime Collection
  Future<List<Document>> getDocumentsFromCollection(String userId) async {
    try {
      final documents = await _databases.listDocuments(
        databaseId: databaseId,
        collectionId: realtimeCollectionId,
        queries: [Query.equal('userId', userId), 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;
    }
  }
}
