<?php

namespace Daylight\Core\Modules\MediaLibrary\Livewire;

use Daylight\Core\Modules\MediaLibrary\Models\Media as MediaModel;
use Illuminate\View\View;
use Livewire\Attributes\On;
use Livewire\Component;

class FileInfo extends Component
{
    public ?int $id = null;

    public ?MediaModel $media = null;

    #[On('select-file')]
    public function setFile(int $id): void
    {
        $this->id = $id;
        $this->media = MediaModel::query()->find($id);
    }

    public function deleteFile(): void
    {
        if (! $this->media || ! $this->media->id) {
            return;
        }

        $fileId = $this->media->id;

        // Delete original file from storage
        if ($this->media->disk && $this->media->path) {
            \Storage::disk($this->media->disk)->delete($this->media->path);
        }

        // Delete all conversion files from storage
        foreach ($this->media->conversions as $conversion) {
            if ($conversion->disk && $conversion->path) {
                \Storage::disk($conversion->disk)->delete($conversion->path);
            }
        }

        // Delete database record (cascade will handle conversions)
        $this->media->delete();

        $this->media = null;
        $this->id = null;
        $this->dispatch('file-deleted', id: $fileId);
    }

    public function render(): View
    {
        return view('daylight::livewire.media.file-info');
    }
}
