package kr.lunaticbum.back.lun.controllers.api

import kr.lunaticbum.back.lun.utils.LogService
import org.jsoup.Jsoup
import org.springframework.http.ResponseEntity
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RequestParam
import org.springframework.web.bind.annotation.RestController
import reactor.core.publisher.Mono
import reactor.core.scheduler.Schedulers
import java.net.SocketTimeoutException

@RestController
@RequestMapping("/api/og")
class OpenGraphController(private val logService: LogService) {

    @GetMapping("/parse")
    fun fetchOpenGraphData(@RequestParam url: String): Mono<ResponseEntity<Map<String, String>>> {
        return Mono.fromCallable {
            try {
                val doc = Jsoup.connect(url).get()
                val title = doc.select("meta[property=og:title]").attr("content")
                val description = doc.select("meta[property=og:description]").attr("content")
                val imageUrl = doc.select("meta[property=og:image]").attr("content")

                val data = mapOf(
                    "title" to (title.ifEmpty { doc.title() }),
                    "description" to description,
                    "thumbnailUrl" to imageUrl
                )
                ResponseEntity.ok(data)
            } catch (e: SocketTimeoutException) {
                logService.log("OG data parsing timed out for URL: $url")
                ResponseEntity.status(408).body(mapOf("error" to "요청 시간이 초과되었습니다."))
            } catch (e: Exception) {
                logService.log("OG data parsing failed for URL: $url, Error: ${e.message}")
                ResponseEntity.badRequest().body(mapOf("error" to "URL 정보를 가져올 수 없습니다."))
            }
        }.subscribeOn(Schedulers.boundedElastic())
    }
}