<?php

declare(strict_types=1);

namespace app\command;

use app\common\library\MallDailyPushBackfill;
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;

#[AsCommand('mall:daily-push:backfill-users', '根据历史每日推送回补用户信息')]
class MallDailyPushBackfillUsers extends Command
{
    protected function configure(): void
    {
        $this->addOption('from', null, InputOption::VALUE_OPTIONAL, '开始日期（含），格式 YYYY-MM-DD');
        $this->addOption('to', null, InputOption::VALUE_OPTIONAL, '结束日期（含），格式 YYYY-MM-DD');
        $this->addOption('limit', null, InputOption::VALUE_OPTIONAL, '最多处理用户数（按 user_id 去重后）', '0');
        $this->addOption('dry-run', null, InputOption::VALUE_NONE, '仅预览，不落库');
    }

    protected function execute(InputInterface $input, OutputInterface $output): int
    {
        $dateFrom = strval($input->getOption('from') ?? '');
        $dateTo = strval($input->getOption('to') ?? '');
        $limitRaw = strval($input->getOption('limit') ?? '0');
        $dryRun = boolval($input->getOption('dry-run'));

        if ($dateFrom !== '' && !$this->isValidDate($dateFrom)) {
            $output->writeln('<error>参数 --from 日期格式错误，需为 YYYY-MM-DD</error>');
            return self::FAILURE;
        }
        if ($dateTo !== '' && !$this->isValidDate($dateTo)) {
            $output->writeln('<error>参数 --to 日期格式错误，需为 YYYY-MM-DD</error>');
            return self::FAILURE;
        }
        if (!is_numeric($limitRaw)) {
            $output->writeln('<error>参数 --limit 必须是数字</error>');
            return self::FAILURE;
        }

        $limit = intval($limitRaw);
        if ($limit < 0) {
            $output->writeln('<error>参数 --limit 不能小于 0</error>');
            return self::FAILURE;
        }

        $service = new MallDailyPushBackfill();
        $result = $service->backfill(
            $dateFrom === '' ? null : $dateFrom,
            $dateTo === '' ? null : $dateTo,
            $limit,
            $dryRun
        );

        $output->writeln('<info>DailyPush 用户回补完成</info>');
        $output->writeln('dry_run: ' . ($result['dry_run'] ? 'true' : 'false'));
        $output->writeln('scanned_rows: ' . strval($result['scanned_rows']));
        $output->writeln('target_users: ' . strval($result['target_users']));
        $output->writeln('processed_users: ' . strval($result['processed_users']));
        $output->writeln('created_users: ' . strval($result['created_users']));
        $output->writeln('updated_users: ' . strval($result['updated_users']));
        $output->writeln('unchanged_users: ' . strval($result['unchanged_users']));
        $output->writeln('failed_users: ' . strval($result['failed_users']));

        $errors = $result['errors'];
        if (is_array($errors) && !empty($errors)) {
            $output->writeln('<comment>错误明细:</comment>');
            foreach ($errors as $err) {
                $uid = strval($err['user_id'] ?? '');
                $msg = strval($err['message'] ?? '');
                $output->writeln("- user_id={$uid}, message={$msg}");
            }
        }

        return self::SUCCESS;
    }

    private function isValidDate(string $value): bool
    {
        $dt = \DateTime::createFromFormat('Y-m-d', $value);
        if (!$dt) {
            return false;
        }
        return $dt->format('Y-m-d') === $value;
    }
}

