import 'package:firebase_database/firebase_database.dart';
import 'package:flutter/material.dart';

import '../../currency.dart';

enum SubscriptionLimitType {
  sales,
  purchase,
  parties,
  products,
  due,
}

extension SubscriptionLimitKey on SubscriptionLimitType {
  String get key {
    switch (this) {
      case SubscriptionLimitType.sales:
        return "saleNumber";
      case SubscriptionLimitType.purchase:
        return "purchaseNumber";
      case SubscriptionLimitType.parties:
        return "partiesNumber";
      case SubscriptionLimitType.products:
        return "products";
      case SubscriptionLimitType.due:
        return "dueNumber";
    }
  }

  String get alert {
    switch (this) {
      case SubscriptionLimitType.sales:
        return "Sale";
      case SubscriptionLimitType.purchase:
        return "Purchase";
      case SubscriptionLimitType.parties:
        return "Parties";
      case SubscriptionLimitType.products:
        return "Product";
      case SubscriptionLimitType.due:
        return "Due Collection";
    }
  }
}

class SubscriptionService {
  static Future<bool> checkLimit({
    required SubscriptionLimitType type,
    required BuildContext context,
  }) async {
    try {
      final dbRef =
          FirebaseDatabase.instance.ref().child(constUserId).child("Subscription").child(type.key);
      dbRef.keepSynced(true);

      final snapshot = await dbRef.get();

      if (!snapshot.exists) {
        _showError(context, "Subscription data not found!");
        return false;
      }

      final value = snapshot.value;

      if (value is int) {
        if (value == -202) return true;
        if (value > 0) return true;
      }

      _showError(context, "Your ${type.alert} limit has been reached!");
      return false;
    } catch (e) {
      _showError(context, "Error checking subscription limit: $e");
      return false;
    }
  }

  static void _showError(BuildContext context, String message) {
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(content: Text(message), backgroundColor: Colors.red),
    );
  }
}
