<?php

namespace App\Livewire\Project;

use App\Models\Environment;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Livewire\Attributes\Locked;
use Livewire\Component;

class DeleteEnvironment extends Component
{
    use AuthorizesRequests;

    #[Locked]
    public int $environment_id;

    public bool $disabled = false;

    public string $environmentName = '';

    public array $parameters;

    public function mount()
    {
        $this->parameters = get_route_parameters();
        $this->environmentName = Environment::ownedByCurrentTeam()->findOrFail($this->environment_id)->name;
    }

    public function delete()
    {
        $this->validate([
            'environment_id' => 'required|int',
        ]);
        $environment = Environment::ownedByCurrentTeam()->findOrFail($this->environment_id);
        $this->authorize('delete', $environment);

        if ($environment->isEmpty()) {
            $environment->delete();

            return redirectRoute($this, 'project.show', ['project_uuid' => $this->parameters['project_uuid']]);
        }

        return $this->dispatch('error', "<strong>Environment {$environment->name}</strong> has defined resources, please delete them first.");
    }
}
