import Foundation
import Testing
@testable import Forji

@MainActor
struct InstanceFormViewTests {
    private func makeInstance(
        server: String = "https://a.com",
        username: String = "user",
        name: String = "Account",
    ) -> ForgejoInstance {
        ForgejoInstance(serverURL: server, username: username, name: name)
    }

    // MARK: - accountAlreadyExists

    @Test func detectsDuplicateServerAndUsername() {
        let existing = [makeInstance(server: "https://a.com", username: "user", name: "Work")]
        #expect(InstanceFormView.accountAlreadyExists(
            serverURL: "https://a.com", username: "user", in: existing,
        ))
    }

    @Test func differentServerIsNotDuplicate() {
        let existing = [makeInstance(server: "https://a.com", username: "user")]
        #expect(!InstanceFormView.accountAlreadyExists(
            serverURL: "https://b.com", username: "user", in: existing,
        ))
    }

    @Test func differentUsernameIsNotDuplicate() {
        let existing = [makeInstance(server: "https://a.com", username: "user")]
        #expect(!InstanceFormView.accountAlreadyExists(
            serverURL: "https://a.com", username: "other", in: existing,
        ))
    }

    @Test func emptyListIsNeverDuplicate() {
        #expect(!InstanceFormView.accountAlreadyExists(
            serverURL: "https://a.com", username: "user", in: [],
        ))
    }

    // MARK: - excluding (edit path)

    @Test func editingInstanceWithoutChangingIdentityIsAllowed() {
        // Editing only the name on an existing account must not flag itself as a duplicate.
        let instance = makeInstance(server: "https://a.com", username: "user", name: "Old")
        #expect(!InstanceFormView.accountAlreadyExists(
            serverURL: "https://a.com", username: "user", in: [instance], excluding: instance,
        ))
    }

    @Test func editingIntoAnotherAccountsIdentityIsRejected() {
        // Two distinct accounts; editing the second to match the first must be caught.
        let first = makeInstance(server: "https://a.com", username: "user", name: "First")
        let second = makeInstance(server: "https://b.com", username: "user", name: "Second")
        #expect(InstanceFormView.accountAlreadyExists(
            serverURL: "https://a.com", username: "user", in: [first, second], excluding: second,
        ))
    }
}
