package com.swoosh.microblog.data.repository

import com.swoosh.microblog.data.model.LinkPreview
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import org.jsoup.Jsoup

object OpenGraphFetcher {

    suspend fun fetch(url: String): LinkPreview? = withContext(Dispatchers.IO) {
        try {
            val doc = Jsoup.connect(url)
                .userAgent("Swoosh/1.0")
                .timeout(10_000)
                .get()

            val title = doc.select("meta[property=og:title]").attr("content")
                .ifBlank { doc.title() }
            val description = doc.select("meta[property=og:description]").attr("content")
                .ifBlank { doc.select("meta[name=description]").attr("content") }
            val imageUrl = doc.select("meta[property=og:image]").attr("content")

            LinkPreview(
                url = url,
                title = title.ifBlank { null },
                description = description.ifBlank { null },
                imageUrl = imageUrl.ifBlank { null }
            )
        } catch (e: Exception) {
            null
        }
    }
}
