<?php

/*
 * This file is part of the Serenity package.
 *
 * (c) CP Creation <web@cpcreation.fr>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Serenity\MediaBundle\Cli;

use League\Flysystem\FilesystemOperator;
use Serenity\MediaBundle\Enum\PathStorage;
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\DependencyInjection\Attribute\Autowire;
use Symfony\Component\Scheduler\Attribute\AsPeriodicTask;

#[AsCommand(
    name: 'serenity:media:clean-temp',
    description: 'clean temp Media',
    hidden: false
)]
#[AsPeriodicTask('12 hours', from: '00:30', schedule: 'default')]
class CleanTempMediaCli extends Command
{
    public function __construct(
        private readonly FilesystemOperator $filesystem,
        #[Autowire(env: 'CLEAN_TEMP')]
        private readonly int $days,
    ) {
        parent::__construct();
    }

    protected function execute(InputInterface $input, OutputInterface $output): int
    {
        $limitDate = new \DateTime("-{$this->days} days");

        $contents = $this->filesystem->listContents(PathStorage::TEMP->value, false);
        foreach ($contents->toArray() as $item) {
            try {
                $lastModified = $item->lastModified();
                if (null === $lastModified) {
                    // alerter si erreur
                }
                if ($lastModified && (new \DateTime())->setTimestamp($lastModified) < $limitDate) {
                    $this->filesystem->delete($item->path());
                }
            } catch (\Exception $exception) {
                // alerter si erreur
            }
        }

        return Command::SUCCESS;
    }
}
