<?php

namespace NewsletterBridge\Services\External;

use NewsletterBridge\Utils\Log;
use NewsletterBridge\Utils\ServiceContainer;
use NewsletterBridge\Services\Newsletter\NewsletterOrchestrator;

/**
 * Classe principale per l'invio delle newsletter
 * Refactored: Ora usa Dependency Injection e separazione responsabilità
 */
class Sender {

    private NewsletterOrchestrator $orchestrator;
    private ServiceContainer $container;

    function __construct( protected \stdClass $config , protected bool $dryrun = false, protected ?int $site_id = null, protected bool $force = false ) {
        $this->config = $config;
        
        // Inizializza il container e configura i servizi
        $this->container = new ServiceContainer();
        $this->container->configureDefaultServices();
        
        // Ottiene l'orchestratore
        $this->orchestrator = $this->container->get('newsletter_orchestrator');
    
        // Genera i file XML
        $this->generateXML();
        
        // INVIO MANUALE 
        if( !$this->dryrun ) $this->sendNewEmail();
        
        Log::stop_script();
    }

    /**
     * Genera i file XML per la newsletter
     *
     * @param string $subject - oggetto imposto manualmente, se necessario
     * @param string $summary - sommario imposto manualmente, se necessario
     * @return void
     */
    function generateXML( bool $generateFiles = true, string $subject = '', string $summary = '') : void {
        $allFeeds = $this->orchestrator->generateXML($this->config, $generateFiles, $subject, $summary, $this->site_id);
        
        if (empty($allFeeds) && $generateFiles) {
            Log::error('Problemi nella generazione dei file XML');
        }
    }

    function sendNewEmail() {
        $this->orchestrator->sendNewsletter($this->config, $this->dryrun, $this->site_id, $this->force);
    }
}