<?php

declare(strict_types=1);

namespace app\common\library;

use Webman\Http\Request;

/**
 * 第三方每日推送原始数据日志（按天写入，默认保留 30 天）
 */
class MallDailyPushRawLogger
{
    public const DEFAULT_RETENTION_DAYS = 30;

    public static function log(Request $request, string $rawBody): void
    {
        $rawBody = trim($rawBody);
        if ($rawBody === '') {
            return;
        }

        $dir = runtime_path('logs/daily_push_raw');
        if (!is_dir($dir) && !mkdir($dir, 0755, true) && !is_dir($dir)) {
            return;
        }

        $entry = [
            'time'    => date('Y-m-d H:i:s'),
            'ip'      => $request->getRealIp(),
            'method'  => $request->method(),
            'path'    => $request->path(),
            'headers' => [
                'X-Request-Id' => strval($request->header('X-Request-Id', '')),
                'X-Timestamp'  => strval($request->header('X-Timestamp', '')),
                'Content-Type' => strval($request->header('Content-Type', '')),
            ],
            'raw' => $rawBody,
        ];

        $logFile = $dir . DIRECTORY_SEPARATOR . 'daily_push_' . date('Y-m-d') . '.log';
        file_put_contents(
            $logFile,
            json_encode($entry, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES) . PHP_EOL,
            FILE_APPEND | LOCK_EX
        );

        self::cleanup($dir);
    }

    private static function cleanup(string $dir): void
    {
        $retentionDays = intval(config('playx.daily_push_raw_log_days', self::DEFAULT_RETENTION_DAYS));
        if ($retentionDays <= 0) {
            return;
        }

        $expireBefore = time() - ($retentionDays * 86400);
        $files = glob($dir . DIRECTORY_SEPARATOR . 'daily_push_*.log');
        if ($files === false) {
            return;
        }

        foreach ($files as $file) {
            if (is_file($file) && filemtime($file) < $expireBefore) {
                @unlink($file);
            }
        }
    }
}
