//
//  MoodReplacementTests.swift
//  Tests iOS
//
//  Mood replacement and duplicate prevention tests.
//

import XCTest

final class MoodReplacementTests: BaseUITestCase {
    override var seedFixture: String? { "single_mood" }

    /// TC-003: Log mood as Good for a day that already has Great → only one entry exists.
    func testReplaceMood_NoDuplicates() {
        let dayScreen = DayScreen(app: app)

        // Seeded data has today as Great. The header may or may not show.
        // If header is visible, log a different mood.
        if dayScreen.moodHeader.waitForExistence(timeout: 3) {
            dayScreen.logMood(.good)
        } else {
            // Today already has an entry. Open detail and change mood.
            let firstEntry = app.firstEntryRow
            guard firstEntry.waitForExistence(timeout: 5) else {
                XCTFail("No entry rows found")
                return
            }
            firstEntry.tap()
            let detailScreen = EntryDetailScreen(app: app)
            detailScreen.assertVisible()
            detailScreen.selectMood(.good)
            detailScreen.dismiss()
            detailScreen.assertDismissed()
        }

        // Verify exactly one entry row exists (no duplicates)
        let entryRows = app.entryRows
        // Wait for at least one entry
        XCTAssertTrue(
            entryRows.firstMatch.waitForExistence(timeout: 5),
            "At least one entry should exist"
        )

        captureScreenshot(name: "mood_replaced_no_duplicates")
    }

    /// TC-158: Log mood twice for same day → verify single entry per date.
    func testNoDuplicateEntries_SameDate() {
        let dayScreen = DayScreen(app: app)

        // If header shows, log Great
        if dayScreen.moodHeader.waitForExistence(timeout: 3) {
            dayScreen.logMood(.great)
        }

        // Now open the entry and change to Bad via detail
        let firstEntry = app.firstEntryRow
        guard firstEntry.waitForExistence(timeout: 8) else {
            XCTFail("No entry found after logging")
            return
        }
        firstEntry.tap()

        let detailScreen = EntryDetailScreen(app: app)
        detailScreen.assertVisible()
        detailScreen.selectMood(.bad)
        detailScreen.dismiss()
        detailScreen.assertDismissed()

        // Verify still only one entry (no duplicate)
        let entryRows = app.entryRows
        XCTAssertTrue(
            entryRows.firstMatch.waitForExistence(timeout: 5),
            "Entry should still exist after mood change"
        )

        captureScreenshot(name: "no_duplicate_entries")
    }
}
