<?php

namespace App\Command;

use App\Repository\UserRepository;
use Symfony\Component\Console\Attribute\AsCommand;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Style\SymfonyStyle;

#[AsCommand(
    name: 'cron:run',
    description: 'Cleanup stale avatars',
)]
class CronRunCommand extends Command
{
    public function __construct(private readonly UserRepository $userRepository)
    {
        parent::__construct();
    }

    protected function configure(): void
    {
        //$this->addOption(name: 'verbose', shortcut: null, mode: InputOption::VALUE_NONE, description: 'Option description');
        //            ->addArgument('arg1', InputArgument::OPTIONAL, 'Argument description')
    }

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

        $verbose = $input->getOption(name: 'verbose');

        $staleCount = $this->deleteStaleAvatars();

        if ($verbose) {
            if ($staleCount > 0) {
                $io->writeln(messages: "There were " . $staleCount . " stale avatars.");
            } else {
                $io->writeln(messages: "There were no stale avatars younger than 24 hours.");
            }
        }

        return Command::SUCCESS;
    }

    private function deleteStaleAvatars(): int
    {
        $avatarDir = dirname(path: __DIR__, levels: 2) . '/public/uploads/avatars';
        $keepTime = 86400; // 24 hours
        $deletedFiles = 0;

        foreach (glob(pattern: $avatarDir . '/*') as $entry) {
            $filectime = filectime(filename: $entry);
            if ($filectime && $filectime + $keepTime < time()) {
                // check if it in use
                if ($user = $this->userRepository->findOneBy(['avatar' => basename(path: $entry)])) {
                    echo basename(path: $entry) . " is in use by: " . $user->getUserIdentifier() . PHP_EOL;
                }
                unlink(filename: $entry);
                $deletedFiles++;
            }

        }
        return $deletedFiles;
    }
}
