<?php

declare(strict_types=1);

final class AssociationBrand
{
    private const MAX_BYTES = 5_000_000;
    private const MIME_EXTENSIONS = ['image/png' => 'png', 'image/jpeg' => 'jpg', 'image/webp' => 'webp'];

    public static function path(): ?string
    {
        $files = glob(self::directory() . '/logo.*') ?: [];
        foreach ($files as $file) {
            if (is_file($file)) {
                return $file;
            }
        }
        return null;
    }

    public static function store(array $upload): void
    {
        $error = (int) ($upload['error'] ?? UPLOAD_ERR_NO_FILE);
        if ($error === UPLOAD_ERR_NO_FILE) {
            return;
        }
        if ($error !== UPLOAD_ERR_OK || !is_uploaded_file((string) ($upload['tmp_name'] ?? ''))) {
            throw new RuntimeException(t('service.logo.upload_failed'));
        }
        if ((int) ($upload['size'] ?? 0) > self::MAX_BYTES) {
            throw new RuntimeException(t('service.logo.too_large'));
        }
        $tmp = (string) $upload['tmp_name'];
        $mime = (new finfo(FILEINFO_MIME_TYPE))->file($tmp);
        $extension = self::MIME_EXTENSIONS[$mime] ?? null;
        if (!$extension) {
            throw new RuntimeException(t('service.logo.format'));
        }
        $dimensions = @getimagesize($tmp);
        if (!$dimensions || $dimensions[0] * $dimensions[1] > 40_000_000) {
            throw new RuntimeException(t('service.logo.dimensions'));
        }
        $dir = self::directory();
        $stored = ImageService::storeUploaded($tmp, $dir, 'association', 'logo');
        $target = $dir . '/logo.' . $stored['extension'];
        foreach (glob($dir . '/logo.*') ?: [] as $old) {
            if ($old !== $stored['path']) {
                @unlink($old);
            }
        }
        if (!rename($stored['path'], $target)) {
            @unlink($stored['path']);
            throw new RuntimeException(t('service.logo.finalize_failed'));
        }
    }

    public static function delete(): void
    {
        foreach (glob(self::directory() . '/logo.*') ?: [] as $file) {
            if (is_file($file)) {
                @unlink($file);
            }
        }
    }
    private static function directory(): string
    {
        return dirname(__DIR__, 2) . '/data/association';
    }
}
