<?php

namespace MintyPHP\Service\User;

use MintyPHP\Service\Image\ImageUploadTrait;

class UserAvatarService
{
    use ImageUploadTrait;

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

    public function isValidUuid(string $uuid): bool
    {
        return self::imageIsValidUuid($uuid);
    }

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

    public function userDir(string $uuid): string
    {
        return $this->storageBase() . '/users/' . $uuid;
    }

    public function findAvatarPath(string $uuid, ?int $size = null): ?string
    {
        if (!$this->isValidUuid($uuid)) {
            return null;
        }
        $dir = $this->userDir($uuid);
        if (!is_dir($dir)) {
            return null;
        }
        if ($size) {
            $size = $this->normalizeSize($size);
            $variant = $this->findVariantPath($dir, $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 hasAvatar(string $uuid): bool
    {
        $path = $this->findAvatarPath($uuid);
        return $path ? is_file($path) : false;
    }

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

    public function saveUpload(string $uuid, array $file): array
    {
        if (!$this->isValidUuid($uuid)) {
            return ['ok' => false, 'error' => t('User not found')];
        }
        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 = $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')];
        }
        // SVG can contain JavaScript — reject files that don't pass the safety check.
        if ($isSvg && !self::imageIsSafeSvg($tmpPath)) {
            return ['ok' => false, 'error' => t('Invalid image file')];
        }

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

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

        // Prefer WebP for variants (better compression); fall back to JPEG if GD lacks WebP support.
        $variantExt = function_exists('imagewebp') ? 'webp' : 'jpg';
        if (!$isSvg && self::imageCanResize()) {
            foreach (self::SIZES as $size) {
                $target = $dir . '/avatar-' . $size . '.' . $variantExt;
                self::imageResizeAndFit($originalPath, $target, $size, $size, $variantExt);
            }
        }

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

    public function saveBinary(string $uuid, string $contents, string $mime = ''): array
    {
        if (!$this->isValidUuid($uuid)) {
            return ['ok' => false, 'error' => t('User not found')];
        }

        $size = strlen($contents);
        if ($size <= 0) {
            return ['ok' => false, 'error' => t('Invalid image file')];
        }
        if ($size > self::MAX_SIZE) {
            return ['ok' => false, 'error' => t('File is too large')];
        }

        $tmpPath = tempnam(sys_get_temp_dir(), 'user-avatar-');
        if ($tmpPath === false) {
            return ['ok' => false, 'error' => t('Upload failed')];
        }
        if (@file_put_contents($tmpPath, $contents) === false) {
            @unlink($tmpPath);
            return ['ok' => false, 'error' => t('Upload failed')];
        }

        $detectedMime = $this->detectMime($tmpPath);
        if ($detectedMime === 'application/octet-stream') {
            $headerMime = strtolower(trim(explode(';', $mime, 2)[0]));
            if (in_array($headerMime, ['image/jpeg', 'image/png', 'image/webp'], true)) {
                $detectedMime = $headerMime;
            }
        }
        $ext = self::imageExtensionForMime($detectedMime, false);
        if (!$ext) {
            @unlink($tmpPath);
            return ['ok' => false, 'error' => t('Invalid image file')];
        }

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

        $this->delete($uuid);
        $originalPath = $dir . '/original.' . $ext;
        // rename() fails across filesystem boundaries (e.g. /tmp → app storage), fall back to copy.
        if (!@rename($tmpPath, $originalPath)) {
            if (!@copy($tmpPath, $originalPath)) {
                @unlink($tmpPath);
                return ['ok' => false, 'error' => t('Upload failed')];
            }
            @unlink($tmpPath);
        }
        @chmod($originalPath, 0644);

        $variantExt = function_exists('imagewebp') ? 'webp' : 'jpg';
        if (self::imageCanResize()) {
            foreach (self::SIZES as $sizeVariant) {
                $target = $dir . '/avatar-' . $sizeVariant . '.' . $variantExt;
                self::imageResizeAndFit($originalPath, $target, $sizeVariant, $sizeVariant, $variantExt);
            }
        }

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

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

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

    private function findVariantPath(string $dir, int $size): ?string
    {
        $matches = glob($dir . '/avatar-' . $size . '.*');
        if (!$matches) {
            return null;
        }
        usort($matches, static function ($a, $b) {
            return filemtime($b) <=> filemtime($a);
        });
        return $matches[0];
    }
}
