<?php

namespace App\Filament\Resources\Media\Pages;

use App\Filament\Resources\Media\MediaResource;
use Filament\Resources\Pages\CreateRecord;
use Illuminate\Support\Facades\Storage;
use Spatie\MediaLibrary\MediaCollections\Models\Media;

class CreateMedia extends CreateRecord
{
    protected static string $resource = MediaResource::class;

    protected ?string $uploadedFile = null;

    protected function mutateFormDataBeforeCreate(array $data): array
    {
        // Extract the file data before creating the media record
        $file = $data['file'] ?? null;
        unset($data['file']);

        // Store file path for later
        $this->uploadedFile = $file;

        // Set required fields for Media model
        $data['model_type'] = $data['model_type'] ?? 'temp';
        $data['model_id'] = $data['model_id'] ?? 0;
        $data['collection_name'] = $data['collection_name'] ?? 'default';
        $data['disk'] = $data['disk'] ?? 'public';
        $data['file_name'] = $file ? basename($file) : '';
        $data['mime_type'] = $file && Storage::disk('public')->exists($file)
            ? Storage::disk('public')->mimeType($file)
            : 'application/octet-stream';
        $data['size'] = $file && Storage::disk('public')->exists($file)
            ? Storage::disk('public')->size($file)
            : 0;
        $data['manipulations'] = [];
        $data['custom_properties'] = [];
        $data['generated_conversions'] = [];
        $data['responsive_images'] = [];

        return $data;
    }

    protected function afterCreate(): void
    {
        if ($this->uploadedFile && $this->record) {
            $disk = Storage::disk('public');

            // Create the directory for this media ID (Spatie structure: {id}/{filename})
            $mediaDirectory = (string) $this->record->id;
            $disk->makeDirectory($mediaDirectory);

            // Move file from temporary upload location to Spatie's expected location
            if ($disk->exists($this->uploadedFile)) {
                $newPath = $mediaDirectory.'/'.$this->record->file_name;
                $disk->move($this->uploadedFile, $newPath);
            }
        }
    }
}
