import Foundation
import SwiftData

struct BatteryConfiguration: Identifiable {
    enum Chemistry: String, CaseIterable, Identifiable {
        case agm = "AGM"
        case gel = "Gel"
        case floodedLeadAcid = "Flooded Lead Acid"
        case lithiumIronPhosphate = "LiFePO4"
        case lithiumIon = "Lithium Ion"

        var id: Self { self }

        var displayName: String {
            rawValue
        }
    }

    let id: UUID
    var name: String
    var nominalVoltage: Double
    var capacityAmpHours: Double
    var chemistry: Chemistry
    var system: ElectricalSystem
    
    init(
        id: UUID = UUID(),
        name: String,
        nominalVoltage: Double = 12.8,
        capacityAmpHours: Double = 100,
        chemistry: Chemistry = .lithiumIronPhosphate,
        system: ElectricalSystem
    ) {
        self.id = id
        self.name = name
        self.nominalVoltage = nominalVoltage
        self.capacityAmpHours = capacityAmpHours
        self.chemistry = chemistry
        self.system = system
    }

    init(savedBattery: SavedBattery, system: ElectricalSystem) {
        self.id = savedBattery.id
        self.name = savedBattery.name
        self.nominalVoltage = savedBattery.nominalVoltage
        self.capacityAmpHours = savedBattery.capacityAmpHours
        self.chemistry = savedBattery.chemistry
        self.system = system
    }

    var energyWattHours: Double {
        nominalVoltage * capacityAmpHours
    }

    func apply(to savedBattery: SavedBattery) {
        savedBattery.name = name
        savedBattery.nominalVoltage = nominalVoltage
        savedBattery.capacityAmpHours = capacityAmpHours
        savedBattery.chemistry = chemistry
        savedBattery.system = system
        savedBattery.timestamp = Date()
    }
}
