<?php

namespace MintyPHP\Module\Security\Service;

use MintyPHP\Service\Image\ImageUploadTrait;

/**
 * Stores and resolves the logo shown on the customer security-check report PDF.
 *
 * A single global asset (the module has no per-tenant settings), kept on the
 * filesystem under storage/security/report-logo (GR-SEC-006: uploads live under
 * storage/ only, are MIME-validated, and SVGs are sanitised). Mirrors the core
 * BrandingLogoService pattern via ImageUploadTrait.
 *
 * @api Consumed by the report-design page (upload/preview/delete) and
 *      SecurityReportPdfService (logo embedding).
 */
final class SecurityReportLogoService
{
    use ImageUploadTrait;

    private const MAX_SIZE = 5242880; // 5 MB
    private const SIZES = [64, 128, 256];
    private const DEFAULT_SIZE = 256;

    public function storageBase(): string
    {
        return self::imageStorageBase();
    }

    public function reportLogoDir(): string
    {
        return $this->storageBase() . '/security/report-logo';
    }

    public function findLogoPath(?int $size = null): ?string
    {
        $dir = $this->reportLogoDir();
        if (!is_dir($dir)) {
            return null;
        }
        if ($size) {
            $variant = $this->findVariantPath($dir, $this->normalizeSize($size));
            if ($variant) {
                return $variant;
            }
        }
        $defaultVariant = $this->findVariantPath($dir, self::DEFAULT_SIZE);
        if ($defaultVariant) {
            return $defaultVariant;
        }
        $original = self::imageFindOriginalPath($dir);

        return $original ?: null;
    }

    public function hasLogo(): bool
    {
        $path = $this->findLogoPath();

        return $path ? is_file($path) : false;
    }

    public function delete(): bool
    {
        $dir = $this->reportLogoDir();
        if (!is_dir($dir)) {
            return true;
        }
        $matches = array_merge(
            glob($dir . '/logo-*.*') ?: [],
            glob($dir . '/logo.*') ?: [],
            glob($dir . '/original.*') ?: []
        );
        foreach ($matches as $file) {
            if (is_file($file)) {
                @unlink($file);
            }
        }

        return true;
    }

    /**
     * @param array<string, mixed> $file A single $_FILES entry (tmp_name, error, size)
     * @return array{ok: bool, error?: string, path?: string, mime?: string}
     */
    public function saveUpload(array $file): array
    {
        if (empty($file) || !isset($file['tmp_name'])) {
            return ['ok' => false, 'error' => t('No file uploaded')];
        }
        if (($file['error'] ?? UPLOAD_ERR_NO_FILE) !== UPLOAD_ERR_OK) {
            return ['ok' => false, 'error' => t('Upload failed')];
        }
        if (($file['size'] ?? 0) > self::MAX_SIZE) {
            return ['ok' => false, 'error' => t('File is too large')];
        }

        $tmpPath = (string) $file['tmp_name'];
        $mime = $this->detectMime($tmpPath);
        $isSvg = self::imageIsSvgUpload($mime, $tmpPath);
        $ext = self::imageExtensionForMime($mime, $isSvg);
        if (!$ext) {
            return ['ok' => false, 'error' => t('Invalid image file')];
        }
        if ($isSvg && !self::imageIsSafeSvg($tmpPath)) {
            return ['ok' => false, 'error' => t('Invalid image file')];
        }

        $dir = $this->reportLogoDir();
        if (!is_dir($dir) && !mkdir($dir, 0755, true) && !is_dir($dir)) {
            return ['ok' => false, 'error' => t('Upload failed')];
        }

        $this->delete();
        $originalPath = $dir . '/original.' . $ext;
        if (!move_uploaded_file($tmpPath, $originalPath)) {
            return ['ok' => false, 'error' => t('Upload failed')];
        }
        @chmod($originalPath, 0644);

        // SVGs are embedded as-is; raster images get downscaled variants when GD is available.
        $variantExt = function_exists('imagewebp') ? 'webp' : 'jpg';
        if (!$isSvg && self::imageCanResize()) {
            foreach (self::SIZES as $size) {
                $target = $dir . '/logo-' . $size . '.' . $variantExt;
                self::imageResizeAndFit($originalPath, $target, $size, $size, $variantExt);
            }
        }

        return ['ok' => true, 'path' => $originalPath, 'mime' => $mime];
    }

    public function detectMime(string $path): string
    {
        return self::imageDetectMime($path);
    }

    private function normalizeSize(int $size): int
    {
        return in_array($size, self::SIZES, true) ? $size : self::DEFAULT_SIZE;
    }

    // Multiple extensions may coexist (e.g. after a format change) — pick the freshest.
    private function findVariantPath(string $dir, int $size): ?string
    {
        $matches = glob($dir . '/logo-' . $size . '.*');
        if (!$matches) {
            return null;
        }
        usort($matches, static fn ($a, $b) => filemtime($b) <=> filemtime($a));

        return $matches[0];
    }
}
