<?php

namespace App\Filament\Resources\DocumentResource\Pages;

use App\Filament\Resources\DocumentResource;
use Filament\Notifications\Notification;
use Filament\Resources\Pages\CreateRecord;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Storage;

class CreateDocument extends CreateRecord
{
    protected static string $resource = DocumentResource::class;

    protected function mutateFormDataBeforeCreate(array $data): array
    {
        $data['uploaded_by'] = Auth::id();

        if (isset($data['file'])) {
            $filePath = $data['file'];

            $data['file_path'] = $filePath;
            $data['file_name'] = $data['file_name'] ?? basename($filePath);
            $data['file_size'] = Storage::disk('local')->size($filePath);
            $data['mime_type'] = Storage::disk('local')->mimeType($filePath);

            unset($data['file']);
        }

        return $data;
    }

    protected function afterCreate(): void
    {
        $conversionService = app(\App\Services\DocumentConversionService::class);
        $conversionService->queueConversion($this->record);
    }

    protected function getCreatedNotification(): ?Notification
    {
        return Notification::make()
            ->success()
            ->title('文档上传成功')
            ->body('文档已成功上传到知识库。');
    }

    protected function getRedirectUrl(): string
    {
        return $this->getResource()::getUrl('index');
    }
}
