<?php
// +----------------------------------------------------------------------
// | onezan-admin 快速开发的管理平台
// +----------------------------------------------------------------------
// | 官方网址：https://www.onezan.cn
// +----------------------------------------------------------------------
// | onezan团队 版权所有 开源版本可自由商用
// +----------------------------------------------------------------------
// | Author: 543885307@qq.com
// +----------------------------------------------------------------------
namespace app\command;

use app\job\admin\CleanupLogsJob;
use think\console\Command;
use think\console\Input;
use think\console\input\Option;
use think\console\Output;


/**
 * Cleanup Operation Logs
 * @package app\command
 */
class CleanupOperationLogs extends Command
{

    /**
     * 配置命令参数和选项
     * @return void
     */
    protected function configure()
    {
        $this->setName('admin:cleanup-operation-logs')
            ->setDescription('Cleanup expired admin operation logs')
            ->addOption('days', null, Option::VALUE_OPTIONAL, 'Retention days', '180')
            ->addOption('limit', null, Option::VALUE_OPTIONAL, 'Max rows per run', '1000')
            ->addOption('dry-run', null, Option::VALUE_NONE, 'Only print matched rows');
    }


    /**
     * 执行日志清理命令
     * @param Input $input
     * @param Output $output
     * @return int
     */
    protected function execute(Input $input, Output $output)
    {
        $daysRaw = $input->getOption('days');
        $days = is_numeric($daysRaw) ? (int)$daysRaw : 180;

        $limitRaw = $input->getOption('limit');
        $limit = is_numeric($limitRaw) ? (int)$limitRaw : 1000;

        $result = $this->job()->handle($days, $limit, (bool)$input->getOption('dry-run'));
        $output->writeln('cutoff=' . (int)($result['cutoff'] ?? 0));
        $output->writeln('matched=' . (int)($result['matched'] ?? 0));
        $output->writeln('deleted=' . (int)($result['deleted'] ?? 0));
        return 0;
    }

    /**
     * 获取清理任务实例
     * @return CleanupLogsJob
     */
    private function job(): CleanupLogsJob
    {
        return app()->make(CleanupLogsJob::class);
    }
}