import XCTest
@testable import PortfolioJournal

final class ReviewPromptServiceTests: XCTestCase {
    private var defaults: UserDefaults!
    private var suiteName: String!

    override func setUp() {
        super.setUp()
        suiteName = UUID().uuidString
        defaults = UserDefaults(suiteName: suiteName)
    }

    override func tearDown() {
        if let suiteName {
            defaults.removePersistentDomain(forName: suiteName)
        }
        super.tearDown()
    }

    func testTriggersAfterMinimumCheckIns() {
        var didRequest = false
        let service = ReviewPromptService(
            userDefaults: defaults,
            dateProvider: { Date(timeIntervalSince1970: 1_000) },
            reviewRequestHandler: { didRequest = true }
        )

        service.recordMonthlyCheckInCompleted()
        service.recordMonthlyCheckInCompleted()
        XCTAssertFalse(didRequest)

        service.recordMonthlyCheckInCompleted()
        XCTAssertTrue(didRequest)
    }

    func testDoesNotTriggerIfPromptedRecently() {
        var didRequest = false
        let now = Date(timeIntervalSince1970: 10_000)
        defaults.set(now, forKey: "reviewPromptLastDate")

        let service = ReviewPromptService(
            userDefaults: defaults,
            dateProvider: { now.addingTimeInterval(60 * 60 * 24 * 10) },
            reviewRequestHandler: { didRequest = true }
        )

        service.recordMonthlyCheckInCompleted()
        service.recordMonthlyCheckInCompleted()
        service.recordMonthlyCheckInCompleted()

        XCTAssertFalse(didRequest)
    }

    func testAchievementPromptTriggersForNewUnlockWhenNotReviewed() {
        let service = ReviewPromptService(
            userDefaults: defaults,
            dateProvider: Date.init,
            reviewRequestHandler: {}
        )

        let shouldAsk = service.shouldAskForAchievementSatisfaction(newlyUnlockedAchievementKeys: ["streak_3"])

        XCTAssertTrue(shouldAsk)
    }

    func testAchievementPromptDoesNotTriggerTwiceForSameAchievement() {
        let service = ReviewPromptService(
            userDefaults: defaults,
            dateProvider: Date.init,
            reviewRequestHandler: {}
        )

        XCTAssertTrue(service.shouldAskForAchievementSatisfaction(newlyUnlockedAchievementKeys: ["streak_3"]))
        XCTAssertFalse(service.shouldAskForAchievementSatisfaction(newlyUnlockedAchievementKeys: ["streak_3"]))
    }

    func testAchievementPromptDoesNotTriggerAfterStoreReviewCompleted() {
        let service = ReviewPromptService(
            userDefaults: defaults,
            dateProvider: Date.init,
            reviewRequestHandler: {}
        )
        service.markStoreReviewCompleted()

        let shouldAsk = service.shouldAskForAchievementSatisfaction(newlyUnlockedAchievementKeys: ["streak_6"])

        XCTAssertFalse(shouldAsk)
    }
}
