package space.nstart.pcp.pcp_mission_planing_service.service.satellite_type

import org.slf4j.LoggerFactory
import org.springframework.stereotype.Component
import space.nstart.pcp.pcp_types_lib.dto.satellite.SatelliteDTO

@Component
class SatelliteMissionTypeFactory(
    private val missionTypes: List<SatelliteMissionType>,
    private val defaultMissionType: DefaultSatelliteMissionType
) {
    private val logger = LoggerFactory.getLogger(SatelliteMissionTypeFactory::class.java)

    private val missionTypesByCode: Map<String, SatelliteMissionType> = missionTypes
        .associateBy { normalize(it.typeCode) }

    fun getBySatellite(satellite: SatelliteDTO): SatelliteMissionType =
        getByTypeCode(satellite.typeCode)

    fun getByTypeCode(typeCode: String?): SatelliteMissionType {
        val normalizedTypeCode = normalize(typeCode)
        if (normalizedTypeCode.isBlank()) {
            return defaultMissionType
        }

        val missionType = missionTypesByCode[normalizedTypeCode]
        if (missionType != null) {
            return missionType
        }

        logger.warn(
            "Mission planner for satellite type '{}' was not found; default mission planner will be used",
            typeCode
        )
        return defaultMissionType
    }

    fun defaultType(): SatelliteMissionType = defaultMissionType

    private fun normalize(value: String?): String = value?.trim()?.uppercase().orEmpty()
}
