<?php

declare(strict_types=1);

namespace App\Filament\Resources\Attachments\Pages;

use App\Filament\Resources\Attachments\AttachmentResource;
use Filament\Resources\Pages\CreateRecord;
use Illuminate\Support\Facades\Storage;

class CreateAttachment extends CreateRecord
{
    protected static string $resource = AttachmentResource::class;

    /**
     * @param  array<string, mixed>  $data
     * @return array<string, mixed>
     */
    protected function mutateFormDataBeforeCreate(array $data): array
    {
        $disk = config('larablog.attachments_disk', 'attachments');
        $path = $data['upload'] ?? null;
        unset($data['upload']);

        if (! is_string($path) || $path === '') {
            throw new \InvalidArgumentException(__('admin.messages.upload_required'));
        }

        $storage = Storage::disk($disk);
        $mime = method_exists($storage, 'mimeType') ? ($storage->mimeType($path) ?: null) : null;
        $allowed = config('larablog.allowed_attachment_mimes', []);
        if (is_string($mime) && $allowed !== [] && ! in_array($mime, $allowed, true)) {
            $storage->delete($path);
            throw new \InvalidArgumentException(__('admin.messages.mime_not_allowed', ['mime' => $mime]));
        }

        $data['disk'] = $disk;
        $data['path'] = $path;
        $data['filename'] = $data['filename'] ?: basename($path);
        $data['mime'] = $mime;
        $data['size'] = $storage->size($path) ?: 0;
        $data['checksum'] = hash('sha256', (string) $storage->get($path));
        $data['synced_at'] = now();
        $data['visibility'] = $data['visibility'] ?? 'public';
        $data['downloads'] = (int) ($data['downloads'] ?? 0);

        return $data;
    }
}
