package kr.lunaticbum.back.lun.model

import lombok.AllArgsConstructor
import lombok.Data
import lombok.NoArgsConstructor
import org.springframework.data.domain.Sort
import org.springframework.data.mongodb.core.mapping.Document
import org.springframework.data.mongodb.repository.Aggregation
import org.springframework.data.mongodb.repository.ReactiveMongoRepository
import reactor.core.publisher.Flux
import reactor.core.publisher.Mono
import java.text.SimpleDateFormat
import java.util.*

@Data
@NoArgsConstructor
@AllArgsConstructor
@Document(collection = "LocationLog")
class LocationLog {
    var id: String? = null // MongoDB ID 필드 명시 권장
    var mFeatureName: String? = null
    var mAddressLines: ArrayList<String> = arrayListOf()
    var mAdminArea: String? = null
    var mSubAdminArea: String? = null
    var mLocality: String? = null
    var mSubLocality: String? = null
    var mThoroughfare: String? = null
    var mSubThoroughfare: String? = null
    var mPremises: String? = null
    var mPostalCode: String? = null
    var mCountryCode: String? = null
    var mCountryName: String? = null
    var mLatitude = 0.0
    var mLongitude = 0.0
    var mPhone: String? = null
    var timeString: String? = null
    var mUrl: String? = null
    var time: Long = 0L
    var userId: String? = null

    var bettween: String? = null // 거리 계산 결과 임시 저장용

    val displayTime: String
        get() {
            if (!this.timeString.isNullOrBlank()) {
                return this.timeString!!
            }
            if (this.time != 0L) {
                val formatter = SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
                return formatter.format(Date(this.time))
            }
            return "[시간 정보 없음]"
        }

    override fun toString(): String {
        return "$mAddressLines ($timeString)"
    }
}

interface LocationLogRepository : ReactiveMongoRepository<LocationLog, String> {
    @Aggregation(pipeline = ["{ \$match: { 'time' : { \$gte: ?0 } } }"])
    fun findRecent(since: Long, sort: Sort): Flux<LocationLog>

    fun findTop30ByOrderByTimeDesc(): Flux<LocationLog>
    fun findFirstByOrderByTimeDesc(): Mono<LocationLog>
    fun findFirstByUserIdOrderByTimeDesc(userId: String): Mono<LocationLog>
}