import Foundation

/// Entspricht `ProfileStore.kt` / `SavedProfile`.
struct SavedProfile: Equatable, Sendable {
    var nickname: String = ""
    var gender: String = ""
    var age: Int = 18
    var country: String = "Germany"
}

final class ProfileStore: @unchecked Sendable {
    private let defaults: UserDefaults
    private let prefix = "ypchat_profile."

    init(defaults: UserDefaults = .standard) {
        self.defaults = defaults
    }

    func read() -> SavedProfile {
        SavedProfile(
            nickname: defaults.string(forKey: prefix + "nickname") ?? "",
            gender: defaults.string(forKey: prefix + "gender") ?? "",
            age: {
                let k = prefix + "age"
                return defaults.object(forKey: k) == nil ? 18 : defaults.integer(forKey: k)
            }(),
            country: defaults.string(forKey: prefix + "country") ?? "Germany"
        )
    }

    func write(_ profile: SavedProfile) {
        defaults.set(profile.nickname.trimmingCharacters(in: .whitespacesAndNewlines), forKey: prefix + "nickname")
        defaults.set(profile.gender, forKey: prefix + "gender")
        defaults.set(profile.age, forKey: prefix + "age")
        defaults.set(profile.country, forKey: prefix + "country")
    }

    func clear() {
        for key in ["nickname", "gender", "age", "country"] {
            defaults.removeObject(forKey: prefix + key)
        }
    }
}
