import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:onsolgo/core/achievement_manager.dart';

class StreakManager {
  static Future<void> updateStreak(String uid) async {
    final docRef = FirebaseFirestore.instance.collection('users').doc(uid);
    final snap = await docRef.get();
    if (!snap.exists) return;

    final data = snap.data() as Map<String, dynamic>;
    final lastVisit = (data['lastVisit'] as Timestamp?)?.toDate();
    int currentStreak = data['streak'] ?? 0;
    final today = DateTime.now();

    if (lastVisit != null) {
      final diff = DateTime(today.year, today.month, today.day).difference(DateTime(lastVisit.year, lastVisit.month, lastVisit.day)).inDays;
      if (diff == 1) {
        currentStreak++;
        await docRef.update({'streak': currentStreak, 'lastVisit': FieldValue.serverTimestamp()});
        // Streak Unlocks
        if (currentStreak >= 2) AchievementManager.unlock(uid, "back_tomorrow");
        if (currentStreak >= 3) AchievementManager.unlock(uid, "3_day_discipline");
        if (currentStreak >= 7) AchievementManager.unlock(uid, "weekly_ritual");
        if (currentStreak >= 30) AchievementManager.unlock(uid, "monthly_reader");
        if (currentStreak >= 60) AchievementManager.unlock(uid, "no_days_off");
      } else if (diff > 1) {
        await docRef.update({'streak': 1, 'lastVisit': FieldValue.serverTimestamp()});
      }
    } else {
      await docRef.update({'streak': 1, 'lastVisit': FieldValue.serverTimestamp()});
      AchievementManager.unlock(uid, "first_login");
    }
  }
}