<?php

declare(strict_types=1);

namespace App\Console\Commands;

use App\Services\Tickets\EmailServiceInterface;
use App\Services\Tickets\TicketEmailProcessor;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Log;

class ProcessTicketEmails extends Command
{
    protected $signature = 'tickets:process-emails';

    protected $description = 'Fetch and process incoming support ticket emails via IMAP';

    public function handle(EmailServiceInterface $emailService, TicketEmailProcessor $processor): int
    {
        if (! config('tickets.polling_enabled')) {
            $this->warn('Ticket email polling is disabled. Set TICKET_EMAIL_POLLING=true to enable.');

            return self::SUCCESS;
        }

        try {
            $emails = $emailService->fetchNewEmails();
            $count = count($emails);

            foreach ($emails as $email) {
                $processor->processEmail($email);
            }

            $this->info("Processed {$count} email(s).");
            Log::info('Ticket email processing complete', ['count' => $count]);

            return self::SUCCESS;
        } catch (\Throwable $e) {
            $this->error('Failed to process ticket emails: '.$e->getMessage());
            Log::error('Ticket email processing failed', [
                'error' => $e->getMessage(),
                'trace' => $e->getTraceAsString(),
            ]);

            return self::FAILURE;
        }
    }
}
