import Foundation
import SwiftData

struct ChargerConfiguration: Identifiable, Hashable {
    let id: UUID
    var name: String
    var inputVoltage: Double
    var outputVoltage: Double
    var maxCurrentAmps: Double
    var maxPowerWatts: Double
    var iconName: String
    var colorName: String
    var system: ElectricalSystem
    var powerSourceType: SavedCharger.PowerSourceType

    init(
        id: UUID = UUID(),
        name: String,
        inputVoltage: Double = LocaleDefaults.mainsVoltage,
        outputVoltage: Double = 14.2,
        maxCurrentAmps: Double = 30.0,
        maxPowerWatts: Double = 0.0,
        iconName: String = "bolt.fill",
        colorName: String = "orange",
        system: ElectricalSystem,
        powerSourceType: SavedCharger.PowerSourceType = .shore
    ) {
        self.id = id
        self.name = name
        self.inputVoltage = inputVoltage
        self.outputVoltage = outputVoltage
        self.maxCurrentAmps = maxCurrentAmps
        self.maxPowerWatts = maxPowerWatts
        self.iconName = iconName
        self.colorName = colorName
        self.system = system
        self.powerSourceType = powerSourceType
    }

    init(savedCharger: SavedCharger, system: ElectricalSystem) {
        self.id = savedCharger.id
        self.name = savedCharger.name
        self.inputVoltage = savedCharger.inputVoltage
        self.outputVoltage = savedCharger.outputVoltage
        self.maxCurrentAmps = savedCharger.maxCurrentAmps
        self.maxPowerWatts = savedCharger.maxPowerWatts
        self.iconName = savedCharger.iconName
        self.colorName = savedCharger.colorName
        self.system = system
        self.powerSourceType = savedCharger.sourceType
    }

    var effectivePowerWatts: Double {
        if maxPowerWatts > 0 {
            return maxPowerWatts
        }
        return outputVoltage * maxCurrentAmps
    }

    func apply(to savedCharger: SavedCharger) {
        savedCharger.name = name
        savedCharger.inputVoltage = inputVoltage
        savedCharger.outputVoltage = outputVoltage
        savedCharger.maxCurrentAmps = maxCurrentAmps
        savedCharger.maxPowerWatts = maxPowerWatts
        savedCharger.iconName = iconName
        savedCharger.colorName = colorName
        savedCharger.system = system
        savedCharger.powerSourceType = powerSourceType.rawValue
        savedCharger.timestamp = Date()
    }
}
