package org.nstart.dep265.requestservice.entity

import jakarta.persistence.CascadeType
import jakarta.persistence.Column
import jakarta.persistence.Entity
import jakarta.persistence.FetchType
import jakarta.persistence.GeneratedValue
import jakarta.persistence.GenerationType
import jakarta.persistence.Id
import jakarta.persistence.OneToMany
import jakarta.persistence.Table
import org.hibernate.annotations.Fetch
import org.hibernate.annotations.FetchMode
import space.nstart.pcp.pcp_types_lib.dto.requests.EarthCellDTO
import space.nstart.pcp.pcp_types_lib.dto.requests.EarthCellWithRequestsDTO

@Entity
@Table(name = "earth_cells")
class EarthCellEntity(
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "cell_id")
    var cellId: Long? = null,

    @Column(name = "cell_num", nullable = false)
    var cellNum: Long = 0,

    @Column(name = "longitude")
    var longitude: Double? = null,

    @Column(name = "latitude")
    var latitude: Double? = null,

    @Column(name = "importance", nullable = false)
    var importance: Double = 0.0,

    @Column(name = "contour_wkt", nullable = false, columnDefinition = "TEXT")
    var contour: String = "",

    /** Привязанные к ячейке фрагменты заявок для legacy earth-grid API. */
    @OneToMany(fetch = FetchType.LAZY, mappedBy = "cell", cascade = [CascadeType.PERSIST, CascadeType.MERGE], orphanRemoval = true)
    @Fetch(FetchMode.SUBSELECT)
    var requestProjections: MutableList<RequestCellEntity> = mutableListOf(),
) {
    fun toDto(): EarthCellDTO {
        val dto = EarthCellDTO(
            id = cellId ?: 0,
            num = cellNum,
            latitude = latitude ?: 0.0,
            longitude = longitude ?: 0.0,
            importance = importance,
            contour = contour,
        )
        return dto
    }

    fun toDtoWithRequests(): EarthCellWithRequestsDTO {
        val dto = EarthCellWithRequestsDTO(
            id = cellId ?: 0,
            num = cellNum,
            latitude = latitude ?: 0.0,
            longitude = longitude ?: 0.0,
            importance = importance,
            contour = contour,
            requests = requestProjections.map { requestProjection -> requestProjection.toDto() },
        )
        return dto
    }
}
