<?php

namespace App\Filament\Resources\DocumentResource\Pages;

use App\Filament\Resources\DocumentResource;
use App\Services\DocumentService;
use Filament\Actions;
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();
        
        // 如果是全局文档，确保 group_id 为 null
        if ($data['type'] === 'global') {
            $data['group_id'] = null;
        }
        
        // 处理文件上传
        if (isset($data['file'])) {
            $filePath = $data['file'];
            
            // 获取原始文件名（由于使用了 preserveFilenames()，basename 就是原始文件名）
            $originalFileName = basename($filePath);
            
            // 保存文件信息
            $data['file_path'] = $filePath;
            $data['file_name'] = $originalFileName; // 保存原始文件名
            $data['file_size'] = Storage::disk('local')->size($filePath);
            $data['mime_type'] = Storage::disk('local')->mimeType($filePath);
            
            // 移除临时的 file 字段
            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');
    }
}
