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

use app\repository\admin\OperationLogRepository;
use think\App;


/**
 * Cleanup Logs Job
 * @package app\job\admin
 */
class CleanupLogsJob
{
    protected App $app;


    public function __construct(App $app)
    {
        $this->app = $app;
    }


    /**
     * 执行日志清理任务
     * @param int $days 保留天数（默认180天）
     * @param int $limit 单次最大删除行数
     * @param bool $dryRun 是否仅统计不删除
     * @return array 清理统计结果
     */
    public function handle(int $days = 180, int $limit = 1000, bool $dryRun = false): array
    {
        if ($days <= 0) {
            $days = 180;
        }
        if ($limit <= 0) {
            $limit = 1000;
        }
        if ($limit > 20000) {
            $limit = 20000;
        }

        $cutoff = time() - ($days * 86400);
        $matched = $this->repository()->countOlderThan($cutoff);
        if ($dryRun) {
            return [
                'cutoff' => $cutoff,
                'matched' => $matched,
                'deleted' => 0,
            ];
        }

        return [
            'cutoff' => $cutoff,
            'matched' => $matched,
            'deleted' => $this->repository()->deleteOlderThan($cutoff, $limit),
        ];
    }

    /**
     * 获取操作日志仓储
     * @return OperationLogRepository
     */
    private function repository(): OperationLogRepository
    {
        return $this->app->make(OperationLogRepository::class);
    }
}