<?php

declare(strict_types=1);

namespace App\Command;

use App\Entity\RenderedAsset;
use App\Enum\RenderStatus;
use App\Message\RenderImageMessage;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\Console\Attribute\AsCommand;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Style\SymfonyStyle;
use Symfony\Component\Messenger\MessageBusInterface;

/**
 * Resets every Ready RenderedAsset to Pending and re-dispatches a render
 * message for it. Use after a renderer change so existing on-disk bins get
 * regenerated with the new pipeline.
 */
#[AsCommand(
    name: 'app:rerender-assets',
    description: 'Reset all rendered assets and re-dispatch render messages',
)]
final class RerenderAssetsCommand extends Command
{
    public function __construct(
        private readonly EntityManagerInterface $em,
        private readonly MessageBusInterface $bus,
    ) {
        parent::__construct();
    }

    protected function execute(InputInterface $input, OutputInterface $output): int
    {
        $io = new SymfonyStyle($input, $output);

        $assets = $this->em->getRepository(RenderedAsset::class)->findAll();
        $count  = 0;

        foreach ($assets as $asset) {
            $asset->setStatus(RenderStatus::Pending)->setFilePath(null);
            $this->bus->dispatch(new RenderImageMessage(
                $asset->getImage()->getId(),
                $asset->getDeviceModel()->value,
                $asset->getOrientation()->value,
            ));
            $count++;
        }

        $this->em->flush();

        $io->success("Reset and re-dispatched $count rendered assets.");
        return Command::SUCCESS;
    }
}
