<?php
declare(strict_types=1);

require_once __DIR__ . '/../config/constants.php';

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

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

    private static function write(string $file, string $message, array $context = []): void
    {
        try {
            if (!is_dir(LOG_PATH)) {
                if (!mkdir(LOG_PATH, 0755, true) && !is_dir(LOG_PATH)) {
                    return; // fail silently, never break API
                }
            }

            $log = date('Y-m-d H:i:s') . ' | ' . $message;

            if (!empty($context)) {
                $log .= ' | ' . json_encode($context, JSON_UNESCAPED_UNICODE);
            }

            $log .= PHP_EOL;

            $filePath = rtrim(LOG_PATH, '/\\') . DIRECTORY_SEPARATOR . $file;

            if (is_writable(LOG_PATH)) {
                file_put_contents($filePath, $log, FILE_APPEND | LOCK_EX);
            }
        } catch (\Throwable $e) {
            // NEVER allow logging failure to crash the application
        }
    }
}
