<?php

namespace App\Support;

use App\Models\Avatar;

class VeoPresenterImage
{
    /** @return array{mimeType: string, data: string}|null */
    public static function fromAvatar(Avatar $avatar): ?array
    {
        $sourcePath = $avatar->source_path;

        if (! is_string($sourcePath) || ! str_starts_with($sourcePath, 'assets/avatars/')) {
            return null;
        }

        $assetDirectory = realpath(public_path('assets/avatars'));
        $resolvedPath = realpath(public_path($sourcePath));

        if ($assetDirectory === false || $resolvedPath === false || ! str_starts_with($resolvedPath, $assetDirectory.DIRECTORY_SEPARATOR)) {
            return null;
        }

        $mimeType = mime_content_type($resolvedPath);

        if (! in_array($mimeType, ['image/png', 'image/jpeg', 'image/webp'], true)) {
            return null;
        }

        $bytes = file_get_contents($resolvedPath);

        return $bytes === false ? null : ['mimeType' => $mimeType, 'data' => base64_encode($bytes)];
    }
}
