import 'package:get/get.dart';
import 'package:on_field_work/helpers/services/api_service.dart';
import 'package:on_field_work/model/document/document_details_model.dart';
import 'package:on_field_work/model/document/document_version_model.dart';

class DocumentDetailsController extends GetxController {
  /// Observables
  var isLoading = false.obs;
  var documentDetails = Rxn<DocumentDetailsResponse>();

  var versions = <DocumentVersionItem>[].obs;
  var isVersionsLoading = false.obs;

  // Loading states for buttons
  var isVerifyLoading = false.obs;
  var isRejectLoading = false.obs;

  /// Fetch document details by id
  Future<void> fetchDocumentDetails(String documentId) async {
    try {
      isLoading.value = true;
      final response = await ApiService.getDocumentDetailsApi(documentId);
      documentDetails.value = response;
    } finally {
      isLoading.value = false;
    }
  }

  /// Fetch document versions by parentAttachmentId
  Future<void> fetchDocumentVersions(String parentAttachmentId) async {
    try {
      isVersionsLoading.value = true;
      final response = await ApiService.getDocumentVersionsApi(
        parentAttachmentId: parentAttachmentId,
      );
      if (response != null) {
        versions.assignAll(response.data.data);
      } else {
        versions.clear();
      }
    } finally {
      isVersionsLoading.value = false;
    }
  }

  /// Verify document
  Future<bool> verifyDocument(String documentId) async {
    try {
      isVerifyLoading.value = true;
      final result =
          await ApiService.verifyDocumentApi(id: documentId, isVerify: true);
      if (result) await fetchDocumentDetails(documentId);
      return result;
    } finally {
      isVerifyLoading.value = false;
    }
  }

  /// Reject document
  Future<bool> rejectDocument(String documentId) async {
    try {
      isRejectLoading.value = true;
      final result =
          await ApiService.verifyDocumentApi(id: documentId, isVerify: false);
      if (result) await fetchDocumentDetails(documentId);
      return result;
    } finally {
      isRejectLoading.value = false;
    }
  }

  /// Fetch Pre-Signed URL for a given version
  Future<String?> fetchPresignedUrl(String versionId) async {
    return await ApiService.getPresignedUrlApi(versionId);
  }

  /// Clear data when leaving the screen
  void clearDetails() {
    documentDetails.value = null;
    versions.clear();
  }
}
