import Foundation

struct LocalDeviceProfile: Codable, Equatable, Identifiable, Sendable {
    var id: String { deviceID }
    var deviceID: String
    var name: String = ""
    var colorTag: String = "blue"

    init(deviceID: String, name: String = "", colorTag: String = "blue") {
        self.deviceID = deviceID
        self.name = name
        self.colorTag = colorTag
    }
}

enum LocalDeviceProfileStore {
    private static let key = "hp_localDeviceProfiles"

    static func allProfiles() -> [LocalDeviceProfile] {
        load().sorted {
            $0.deviceID.localizedCaseInsensitiveCompare($1.deviceID) == .orderedAscending
        }
    }

    static func profile(for deviceID: String) -> LocalDeviceProfile {
        guard !deviceID.isEmpty else { return LocalDeviceProfile(deviceID: deviceID) }
        return load().first { $0.deviceID == deviceID } ?? LocalDeviceProfile(deviceID: deviceID)
    }

    static func save(_ profile: LocalDeviceProfile) {
        guard !profile.deviceID.isEmpty else { return }
        var profiles = load()
        if let index = profiles.firstIndex(where: { $0.deviceID == profile.deviceID }) {
            profiles[index] = profile
        } else {
            profiles.append(profile)
        }
        save(profiles)
    }

    static func removeAll() {
        UserDefaults.standard.removeObject(forKey: key)
    }

    private static func load() -> [LocalDeviceProfile] {
        guard let data = UserDefaults.standard.data(forKey: key) else { return [] }
        return (try? JSONDecoder().decode([LocalDeviceProfile].self, from: data)) ?? []
    }

    private static func save(_ profiles: [LocalDeviceProfile]) {
        let sorted = profiles.sorted {
            $0.deviceID.localizedCaseInsensitiveCompare($1.deviceID) == .orderedAscending
        }
        UserDefaults.standard.set(try? JSONEncoder().encode(sorted), forKey: key)
    }
}
