<?php

namespace App\Support;

use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Log;

class PaymentLogger
{
    private const PAYMENT_GATEWAY = 'razorpay';
    private static ?\Psr\Log\LoggerInterface $dailyLogger = null;
    private static ?string $dailyLoggerDate = null;

    /**
     * Write payment logs to default log and date-wise payment log file.
     */
    public static function write(string $level, string $message, array $context = []): void
    {
        $normalizedContext = self::normalizeContext($context);

        Log::log($level, $message, $normalizedContext);

        try {
            self::getDailyLogger()->log($level, $message, $normalizedContext);
        } catch (\Throwable $e) {
            Log::warning('Payment logger daily file write failed', [
                'approx_time' => now()->toDateTimeString(),
                'error' => $e->getMessage(),
            ]);
        }
    }

    public static function info(string $message, array $context = []): void
    {
        self::write('info', $message, $context);
    }

    public static function warning(string $message, array $context = []): void
    {
        self::write('warning', $message, $context);
    }

    public static function error(string $message, array $context = []): void
    {
        self::write('error', $message, $context);
    }

    private static function normalizeContext(array $context): array
    {
        return array_merge([
            'approx_time' => now()->toDateTimeString(),
            'gateway' => self::PAYMENT_GATEWAY,
            'order_id' => $context['order_id'] ?? null,
            'payment_id' => $context['payment_id'] ?? ($context['razorpay_payment_id'] ?? null),
        ], $context);
    }

    private static function getDailyLogger(): \Psr\Log\LoggerInterface
    {
        $today = now()->format('Y-m-d');
        if (self::$dailyLogger !== null && self::$dailyLoggerDate === $today) {
            return self::$dailyLogger;
        }

        $logDirectory = storage_path('logs/payments');
        if (!File::exists($logDirectory)) {
            File::ensureDirectoryExists($logDirectory);
        }

        self::$dailyLogger = Log::build([
            'driver' => 'single',
            'path' => $logDirectory . '/payment-' . $today . '.log',
            'level' => 'debug',
            'replace_placeholders' => true,
        ]);
        self::$dailyLoggerDate = $today;

        return self::$dailyLogger;
    }
}
