<?php

namespace App\Rules;

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

class MarkdownFileExtension implements ValidationRule
{
    /**
     * @param  array<int, string>  $allowedExtensions
     */
    public function __construct(
        private readonly array $allowedExtensions = ['md', 'markdown', 'txt']
    ) {
    }

    public function validate(string $attribute, mixed $value, Closure $fail): void
    {
        if (blank($value)) {
            return;
        }

        $file = is_array($value) ? ($value[0] ?? null) : $value;

        if (!($file instanceof UploadedFile)) {
            return;
        }

        $ext = strtolower((string) $file->getClientOriginalExtension());

        if (!in_array($ext, $this->allowedExtensions, true)) {
            $fail('Markdown 文件格式不正确，请上传 .md / .markdown / .txt');
        }
    }
}

