<?php

declare(strict_types=1);

namespace Install\Services;

final class InstallationLogger
{
    private string $filePath;

    public function __construct()
    {
        $directory = PROJECT_PATH
            . DIRECTORY_SEPARATOR
            . 'storage'
            . DIRECTORY_SEPARATOR
            . 'install';

        if (!is_dir($directory)) {
            if (!mkdir($directory, 0775, true) && !is_dir($directory)) {
                throw new \RuntimeException(
                    'Impossible de créer le dossier storage/install.'
                );
            }
        }

        $this->filePath = $directory
            . DIRECTORY_SEPARATOR
            . 'install.log';
    }

    public function reset(): void
    {
        file_put_contents(
            $this->filePath,
            '',
            LOCK_EX
        );
    }

    public function write(
        string $level,
        string $message
    ): void {
        $line = sprintf(
            "[%s] %-7s %s%s",
            date('Y-m-d H:i:s'),
            strtoupper($level),
            $message,
            PHP_EOL
        );

        file_put_contents(
            $this->filePath,
            $line,
            FILE_APPEND | LOCK_EX
        );
    }

    public function path(): string
    {
        return $this->filePath;
    }
}
