// Copyright (C) 2026 Jason M. Schwefel. All Rights Reserved.
package com.coldboreballisticsllc.scopedope.data.ammo

import androidx.room.ColumnInfo
import androidx.room.Entity
import androidx.room.Index
import androidx.room.PrimaryKey
import com.coldboreballisticsllc.scopedope.domain.model.AmmoLoad
import com.coldboreballisticsllc.scopedope.ballistics.BcModel

@Entity(
    tableName = "ammo",
    indices = [Index("caliber"), Index(value = ["caliber", "name"], unique = true)],
)
data class AmmoEntity(
    @PrimaryKey(autoGenerate = true)
    val id:              Int     = 0,
    val caliber:         String,
    val name:            String,
    @ColumnInfo(name = "velocity_fps")
    val velocityFps:     Int,
    @ColumnInfo(name = "bc_g1")
    val bcG1:            Double,
    @ColumnInfo(name = "bc_g7")
    val bcG7:            Double,
    @ColumnInfo(name = "is_user_defined")
    val isUserDefined:            Boolean = false,
    @ColumnInfo(name = "bullet_weight_gr")
    val bulletWeightGr:           Double  = 0.0,
    @ColumnInfo(name = "mv_sensitivity_fps_per_f")
    val mvSensitivityFpsPerF:     Double  = 0.0,
    @ColumnInfo(name = "mv_reference_temp_f")
    val mvReferenceTempF:         Double  = 59.0,
    @ColumnInfo(name = "form_factor")
    val formFactor:               Double  = 0.0,
    @ColumnInfo(name = "bullet_diameter_mm")
    val bulletDiameterMm:         Double  = 0.0,
    @ColumnInfo(name = "bullet_length_mm")
    val bulletLengthMm:           Double  = 0.0,
) {
    /** Map to the domain model using the user's preferred BC model. */
    fun toDomain(preferredModel: BcModel = BcModel.G7): AmmoLoad {
        val (bc, model) = when {
            preferredModel == BcModel.G7 && bcG7 > 0.0 -> bcG7 to BcModel.G7
            preferredModel == BcModel.G1 && bcG1 > 0.0 -> bcG1 to BcModel.G1
            bcG7 > 0.0                                  -> bcG7 to BcModel.G7  // fallback: G7 available
            bcG1 > 0.0                                  -> bcG1 to BcModel.G1  // fallback: G1 available
            else                                        -> 0.0 to preferredModel // both zero; engine validation will reject
        }
        return AmmoLoad(
            id                    = id,
            caliber               = caliber,
            name                  = name,
            muzzleVelFps          = velocityFps,
            bc                    = bc,
            bcModel               = model,
            bcG1                  = bcG1,
            bcG7                  = bcG7,
            formFactor            = formFactor,
            bulletDiameterMm      = bulletDiameterMm,
            bulletLengthMm        = bulletLengthMm,
            bulletWeightGr        = bulletWeightGr,
            mvSensitivityFpsPerF  = mvSensitivityFpsPerF,
            mvReferenceTempF      = mvReferenceTempF,
            isUserDefined         = isUserDefined,
        )
    }
}
