<?php

namespace classes;

use traits\minio_t;

class error_report_store
{
    use minio_t;

    public function __construct()
    {
        self::setBucket('uploads');
    }

    public function storeScreenshot(string $mimeType, string $contents): array
    {
        $extension = match ($mimeType) {
            'image/webp' => 'webp',
            'image/jpeg' => 'jpg',
            default => 'png',
        };

        $datePath = date('Y/m');
        $key = sprintf('error-reports/%s/%s.%s', $datePath, bin2hex(random_bytes(16)), $extension);

        if (!self::createObject($key, $contents)) {
            throw new \RuntimeException('Could not store error report screenshot.');
        }

        return [
            'key' => $key,
            'mime_type' => $mimeType,
            'size_bytes' => strlen($contents),
        ];
    }

    public function screenshotUrl(string $key): ?string
    {
        $key = trim($key);
        if ($key === '') {
            return null;
        }

        return self::getPresignedUrl($key, 1200, false);
    }
}
