<?php

declare(strict_types=1);

namespace App\Core;

/**
 * Logger
 *
 * Simple leveled file logger. One file per day per level bucket keeps
 * individual log files small and greppable in production
 * (storage/logs/2026-07-13-error.log, etc.). Not PSR-3 itself (no
 * Composer dependency required to get logging working on first boot),
 * but mirrors the PSR-3 level names and method signatures closely
 * enough that swapping in Monolog later is a drop-in change.
 */
final class Logger
{
    private const LEVELS = ['debug', 'info', 'warning', 'error', 'critical'];

    private static ?string $logDir = null;

    public static function setLogDirectory(string $path): void
    {
        self::$logDir = rtrim($path, '/');
    }

    public static function debug(string $message, array $context = []): void
    {
        self::log('debug', $message, $context);
    }

    public static function info(string $message, array $context = []): void
    {
        self::log('info', $message, $context);
    }

    public static function warning(string $message, array $context = []): void
    {
        self::log('warning', $message, $context);
    }

    public static function error(string $message, array $context = []): void
    {
        self::log('error', $message, $context);
    }

    public static function critical(string $message, array $context = []): void
    {
        self::log('critical', $message, $context);
    }

    public static function log(string $level, string $message, array $context = []): void
    {
        if (!in_array($level, self::LEVELS, true)) {
            $level = 'info';
        }

        $dir = self::$logDir ?? (dirname(__DIR__, 2) . '/storage/logs');

        if (!is_dir($dir)) {
            @mkdir($dir, 0775, true);
        }

        $file = sprintf('%s/%s-%s.log', $dir, date('Y-m-d'), $level);

        $line = sprintf(
            '[%s] %s: %s %s%s',
            date('Y-m-d H:i:s'),
            strtoupper($level),
            $message,
            $context === [] ? '' : json_encode($context, JSON_UNESCAPED_SLASHES),
            PHP_EOL
        );

        // Suppress warnings if storage/logs is somehow not writable —
        // logging must never be the thing that crashes the request.
        @file_put_contents($file, $line, FILE_APPEND | LOCK_EX);
    }
}
