<?php

namespace App\Filament\Resources\Media\Pages;

use App\Filament\Resources\Media\MediaResource;
use Filament\Actions\DeleteAction;
use Filament\Actions\ViewAction;
use Filament\Resources\Pages\EditRecord;
use Illuminate\Support\Facades\Storage;

class EditMedia extends EditRecord
{
    protected static string $resource = MediaResource::class;

    protected ?string $uploadedFile = null;

    protected function getHeaderActions(): array
    {
        return [
            ViewAction::make(),
            DeleteAction::make(),
        ];
    }

    protected function mutateFormDataBeforeSave(array $data): array
    {
        // Extract the file data if a new file was uploaded
        $file = $data['file'] ?? null;
        unset($data['file']);

        // Only update file-related fields if a new file was uploaded
        if ($file && $file !== $this->record->getPathRelativeToRoot()) {
            $this->uploadedFile = $file;

            // Keep the original file_name to prevent breaking existing references
            // $data['file_name'] is not updated - we preserve the original filename
            $data['mime_type'] = Storage::disk('public')->exists($file)
                ? Storage::disk('public')->mimeType($file)
                : 'application/octet-stream';
            $data['size'] = Storage::disk('public')->exists($file)
                ? Storage::disk('public')->size($file)
                : 0;
        }

        return $data;
    }

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

            // Delete old file if it exists
            $oldPath = $mediaDirectory.'/'.$this->record->getOriginal('file_name');
            if ($disk->exists($oldPath)) {
                $disk->delete($oldPath);
            }

            // Move new file to Spatie's expected location using the original filename
            if ($disk->exists($this->uploadedFile)) {
                $disk->makeDirectory($mediaDirectory);
                // Use the original file_name to preserve existing references
                $newPath = $mediaDirectory.'/'.$this->record->file_name;
                $disk->move($this->uploadedFile, $newPath);
            }

            // Redirect to the same page to refresh the form state
            $this->redirect(static::getUrl(['record' => $this->record]), navigate: true);
        }
    }
}
