package com.swoosh.microblog.data

import com.swoosh.microblog.data.model.FeedPost

/**
 * Utility functions for sharing posts via Android share sheet and clipboard.
 */
object ShareUtils {

    /**
     * Constructs a post URL from the Ghost base URL and the post slug.
     * Ghost default URL format: https://yourblog.com/slug/
     *
     * @param baseUrl The Ghost instance base URL (e.g. "https://blog.example.com" or "https://blog.example.com/")
     * @param slug The post slug (e.g. "my-first-post")
     * @return The full post URL with trailing slash
     */
    fun getPostUrl(baseUrl: String, slug: String): String {
        val normalizedBase = baseUrl.trimEnd('/')
        val normalizedSlug = slug.trim('/')
        return "$normalizedBase/$normalizedSlug/"
    }

    /**
     * Resolves the shareable URL for a post.
     * Prefers the GhostPost url field if available, otherwise constructs from baseUrl + slug.
     *
     * @param post The FeedPost to get the URL for
     * @param baseUrl The Ghost instance base URL
     * @return The post URL, or null if no slug or url is available
     */
    fun resolvePostUrl(post: FeedPost, baseUrl: String?): String? {
        // Prefer the url field from the Ghost API response
        if (!post.url.isNullOrBlank()) {
            return post.url
        }
        // Fall back to constructing from base URL + slug
        if (!post.slug.isNullOrBlank() && !baseUrl.isNullOrBlank()) {
            return getPostUrl(baseUrl, post.slug)
        }
        return null
    }

    /**
     * Formats share content for a post.
     * Includes the first 280 chars of text content, then "Read more:" link.
     * For posts with link previews, the linked URL is included.
     *
     * @param post The FeedPost to format
     * @param postUrl The resolved URL for the post
     * @return Formatted share text
     */
    fun formatShareContent(post: FeedPost, postUrl: String): String {
        val content = buildString {
            // Post text content, truncated to 280 chars
            val text = post.textContent.trim()
            if (text.isNotEmpty()) {
                if (text.length > 280) {
                    append(text.take(280))
                    append("...")
                } else {
                    append(text)
                }
            }

            // If there's a link preview URL, include it
            if (!post.linkUrl.isNullOrBlank()) {
                if (isNotEmpty()) append("\n\n")
                append(post.linkUrl)
            }

            // Always include the post URL
            if (isNotEmpty()) append("\n\n")
            append("Read more: $postUrl")
        }
        return content
    }
}
