package dev.adriankuta.flights.model.repository.mappers

import dev.adriankuta.flights.domain.types.Flight
import dev.adriankuta.flights.domain.types.RegularFare
import dev.adriankuta.flights.domain.types.Segment
import dev.adriankuta.flights.domain.types.Trip
import dev.adriankuta.flights.domain.types.TripDate
import dev.adriankuta.flights.domain.types.TripFare
import dev.adriankuta.flights.domain.types.TripFlight
import dev.adriankuta.model.data.api.entities.FlightResponse
import kotlinx.datetime.LocalDateTime
import dev.adriankuta.model.data.api.entities.RegularFare as ApiRegularFare
import dev.adriankuta.model.data.api.entities.Segment as ApiSegment
import dev.adriankuta.model.data.api.entities.Trip as ApiTrip
import dev.adriankuta.model.data.api.entities.TripDate as ApiTripDate
import dev.adriankuta.model.data.api.entities.TripFare as ApiTripFare
import dev.adriankuta.model.data.api.entities.TripFlight as ApiTripFlight

internal fun FlightResponse.toDomain(): Flight {
    return Flight(
        currency = currency ?: "",
        currPrecision = currPrecision ?: 0,
        trips = trips.orEmpty().map { it.toDomain() },
    )
}

internal fun ApiTrip.toDomain(): Trip {
    return Trip(
        dates = dates.orEmpty().map { it.toDomain() },
        origin = origin ?: "",
        destination = destination ?: "",
    )
}

internal fun ApiTripDate.toDomain(): TripDate {
    return TripDate(
        dateOut = dateOut?.let { LocalDateTime.parse(it).date },
        flights = flights.orEmpty().map { it.toDomain() },
    )
}

internal fun ApiTripFlight.toDomain(): TripFlight {
    return TripFlight(
        faresLeft = faresLeft ?: 0,
        regularFare = regularFare?.toDomain() ?: RegularFare(emptyList()),
        flightNumber = flightNumber ?: "",
        dateTimes = dateTimes.orEmpty(),
        duration = duration ?: "",
        segments = segments.orEmpty().map { it.toDomain() },
        operatedBy = operatedBy ?: "",
    )
}

internal fun ApiRegularFare.toDomain(): RegularFare {
    return RegularFare(
        fares = fares.orEmpty().map { it.toDomain() },
    )
}

internal fun ApiTripFare.toDomain(): TripFare {
    return TripFare(
        type = type ?: "",
        amount = amount ?: 0.0,
        count = count ?: 0,
    )
}

internal fun ApiSegment.toDomain(): Segment {
    return Segment(
        origin = origin ?: "",
        destination = destination ?: "",
        flightNumber = flightNumber ?: "",
        dateTimes = dateTimes.orEmpty(),
        duration = duration ?: "",
    )
}
