<?php

namespace App\Rules;

use Closure;
use Exception;
use Illuminate\Contracts\Validation\ValidationRule;
use Illuminate\Http\UploadedFile;

class MimeMatch implements ValidationRule
{
    /**
     * Run the validation rule.
     *
     * @param  \Closure(string): \Illuminate\Translation\PotentiallyTranslatedString  $fail
     */
    public function validate(string $attribute, mixed $value, Closure $fail): void
    {
        $file = request()->file($attribute);

        if (!$file) {
            $fail('The uploaded :attribute are empty.');
        }

        try {
            if (is_array($file)) {
                foreach ($file as $value) {
                    $this->compareMime($value);
                }
            } else {
                $this->compareMime($file);
            }
        } catch (\Throwable $th) {
            $fail('The uploaded :attribute are invalid.');
        }
    }

    private function compareMime($file) {
        if ($file instanceof UploadedFile) {
            // original file content mime vs mime on generate from browser
            if ($file->getMimeType() !== $file->getClientMimeType()) {
                throw new Exception();
            }
        } else {
            throw new Exception();
        }
    }
}
