import ForgejoKit
import Foundation
import SwiftUI
import Testing

@testable import Forji

private func makeIssue(id: Int, updatedAt: Date = Date()) -> ForgejoKit.Issue {
    ForgejoKit.Issue(
        id: id, number: id,
        title: "Issue \(id)", body: nil, state: "open",
        user: User(id: 1, login: "u", fullName: "U", email: "u@e", avatarUrl: nil, isAdmin: false, created: Date()),
        createdAt: Date(), updatedAt: updatedAt, comments: 0,
    )
}

private typealias SUT = SearchableOverviewView<EmptyView, EmptyView, EmptyView>

@Suite("deduplicateAndSort")
struct DeduplicateAndSortTests {
    @Test func emptyBatchesReturnEmpty() {
        let result = SUT.deduplicateAndSort([[], []])
        #expect(result.isEmpty)
    }

    @Test func singleBatchPreserved() {
        let now = Date()
        let issues = [
            makeIssue(id: 1, updatedAt: now),
            makeIssue(id: 2, updatedAt: now.addingTimeInterval(-10)),
        ]
        let result = SUT.deduplicateAndSort([issues])
        #expect(result.map { $0.id } == [1, 2])
    }

    @Test func duplicatesRemovedKeepsFirst() {
        let a = makeIssue(id: 1, updatedAt: Date())
        let b = makeIssue(id: 1, updatedAt: Date().addingTimeInterval(-100))
        let result = SUT.deduplicateAndSort([[a], [b]])
        #expect(result.count == 1)
        #expect(result[0].id == 1)
    }

    @Test func sortedByUpdatedAtDescending() {
        let old = makeIssue(id: 1, updatedAt: Date().addingTimeInterval(-200))
        let mid = makeIssue(id: 2, updatedAt: Date().addingTimeInterval(-100))
        let recent = makeIssue(id: 3, updatedAt: Date())
        let result = SUT.deduplicateAndSort([[old], [recent], [mid]])
        #expect(result.map { $0.id } == [3, 2, 1])
    }

    @Test func duplicatesAcrossMultipleBatches() {
        let now = Date()
        let a = makeIssue(id: 1, updatedAt: now)
        let b = makeIssue(id: 2, updatedAt: now.addingTimeInterval(-10))
        let c = makeIssue(id: 3, updatedAt: now.addingTimeInterval(-20))
        let result = SUT.deduplicateAndSort([[a, b], [b, c], [a, c]])
        #expect(result.map { $0.id } == [1, 2, 3])
    }
}
