import UIKit
import StoreKit

@MainActor
final class ReviewPromptService {
    static let shared = ReviewPromptService()

    private let reviewCompletedKey = "review_funnel_completed"
    private let lastPromptedCompletedWeeksKey = "review_funnel_last_prompted_completed_weeks"
    private let minimumCompletedWeeksToStart = 2
    private let promptIntervalWeeks = 2

    private init() {}

    func shouldShowFunnelAfterWeekCompletion(completedWeeks: Int) -> Bool {
        guard !hasCompletedReviewFlow else { return false }
        guard completedWeeks >= minimumCompletedWeeksToStart else { return false }
        guard completedWeeks % promptIntervalWeeks == 0 else { return false }

        let lastPrompted = UserDefaults.standard.integer(forKey: lastPromptedCompletedWeeksKey)
        return completedWeeks > lastPrompted
    }

    func markFunnelShown(completedWeeks: Int) {
        UserDefaults.standard.set(completedWeeks, forKey: lastPromptedCompletedWeeksKey)
    }

    func markReviewCompleted() {
        UserDefaults.standard.set(true, forKey: reviewCompletedKey)
    }

    func requestFromSettings() {
        requestReview()
    }

    var hasCompletedReviewFlow: Bool {
        UserDefaults.standard.bool(forKey: reviewCompletedKey)
    }

    func requestReview() {
        guard let scene = UIApplication.shared.connectedScenes
            .compactMap({ $0 as? UIWindowScene })
            .first(where: { $0.activationState == .foregroundActive }) else { return }

        SKStoreReviewController.requestReview(in: scene)
    }
}
