<?php

namespace App\Sms\Command;

use App\Sms\Entity\SmsMessageTemplate;
use App\Sms\Repository\SmsMessageTemplateRepository;
use Symfony\Component\Console\Attribute\AsCommand;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;

#[AsCommand(
    name: 'app:seed-sms-message-templates',
    description: 'متن پیش‌فرض پیامک‌های سیستمی را برای تگ‌هایی که هنوز رکورد ندارند می‌سازد',
)]
class SeedSmsMessageTemplatesCommand extends Command
{
    public function __construct(private readonly SmsMessageTemplateRepository $repo)
    {
        parent::__construct();
    }

    protected function execute(InputInterface $input, OutputInterface $output): int
    {
        $created = 0;
        $backfilled = 0;
        foreach (SmsMessageTemplate::DEFAULTS as $tag => $def) {
            $existing = $this->repo->findByTag($tag);
            if ($existing !== null) {
                if ($existing->getKavenegarTemplate() === null) {
                    $existing->setKavenegarTemplate($def['kavenegar_template']);
                    $existing->setTokenMap($def['token_map']);
                    $backfilled++;
                }
                continue;
            }
            $this->repo->save(
                new SmsMessageTemplate(
                    $tag,
                    $def['title'],
                    $def['body'],
                    $def['variables'],
                    $def['kavenegar_template'],
                    $def['token_map'],
                ),
                false,
            );
            $created++;
        }
        $this->repo->getEntityManager()->flush();

        $output->writeln(sprintf('Seeded %d, backfilled %d sms message templates.', $created, $backfilled));
        return Command::SUCCESS;
    }
}
