<?php

namespace NewsletterBridge\Services\Content;

use NewsletterBridge\Config\CdnConfig;
use NewsletterBridge\Services\ImgCDN\CDNFactory;

/**
 * Responsabilità: Processamento template post
 * Single Responsibility: Solo logica di processamento template
 */
class PostTemplateProcessor {
    
    /**
     * Processa una lista di post WordPress in template per feed
     */
    public function processPosts(array $posts): array {
        $result = [];
        
        foreach ($posts as $post) {
            $result[] = $this->processPost($post);
        }
        
        return $result;
    }
    
    /**
     * Processa un singolo post in template
     */
    private function processPost(\WP_Post $post): object {
        $template = new \stdClass();
        
        $template->id = $post->ID;
        $template->title = $post->post_title;
        $template->date = mysql2date('D, d M Y H:i:s +0000', $post->post_date, false);
        $template->author = get_the_author_meta('display_name', $post->post_author);
        $template->image = $this->getPostImage($post->ID);
        $template->description = $this->getPostDescription($post);
        $template->link = get_permalink($post->ID);
        
        return $template;
    }
    
    /**
     * Ottiene l'immagine del post
     */
    private function getPostImage(int $post_id): ?string {
        $thumbnail_id = get_post_thumbnail_id($post_id);
        if (!$thumbnail_id) {
            return null;
        }

        $imageUrl = wp_get_attachment_image_url($thumbnail_id, 'hero');
        if (!$imageUrl) {
            $imageUrl = wp_get_attachment_image_url($thumbnail_id, 'full');
        }

        if (!$imageUrl) {
            return null;
        }

        $config = CdnConfig::getConfig();
        $args = [
            'width' => $config->default_width,
            'height' => $config->default_height,
            'quality' => $config->default_quality,
            'format' => $config->default_format,
            'resize' => $config->resize_mode,
        ];

        try {
            $cdn = CDNFactory::getCDN($config->provider);
            $cdnUrl = $cdn->getUrl($imageUrl, $args);
            return $cdnUrl ?: $imageUrl;
        } catch (\Throwable $e) {
            if (function_exists('error_log')) {
                error_log('[newsletter_bridge] CDN image error: ' . $e->getMessage());
            }
            return $imageUrl;
        }
    }
    
    /**
     * Ottiene la descrizione del post
     */
    private function getPostDescription(\WP_Post $post): string {
        // Prova prima l'excerpt
        if (!empty($post->post_excerpt)) {
            return $post->post_excerpt;
        }
        
        // Poi il contenuto (primi 200 caratteri)
        $content = strip_tags($post->post_content);
        return wp_trim_words($content, 30, '...');
    }
}
