<?php

namespace App\Livewire\Environments;

use App\Models\Clients\Client;
use App\Models\Environments\Environment;
use App\Models\Environments\Type;
use Livewire\Component;

class Edit extends Component
{
    public Environment $environment;
    public string $name = '';
    public string $domain = '';
    public ?string $description = null;
    public string $version = '';
    public string $env = 'local';
    public ?int $client_id = null;
    public ?int $type_id = null;
    public bool $active = true;

    public function mount(Environment $environment)
    {
        $this->environment = $environment;
        $this->name = $environment->name ?? '';
        $this->domain = $environment->domain ?? '';
        $this->description = $environment->description;
        $this->version = $environment->version ?? '';
        $this->env = $environment->env ?? 'local';
        $this->client_id = $environment->client_id;
        $this->type_id = $environment->type_id;
        $this->active = $environment->active ?? true;
    }

    protected function rules()
    {
        return [
            'name' => 'required|string|max:255',
            'domain' => 'required|string|max:255|unique:environments,domain,' . $this->environment->id,
            'description' => 'nullable|string',
            'version' => 'required|string|max:50',
            'env' => 'required|string',
            'client_id' => 'nullable|exists:clients,id',
            'type_id' => 'nullable|exists:types,id',
            'active' => 'sometimes|accepted',
        ];
    }

    public function update()
    {
        $this->authorize('admin.environments.edit');
        
        $validated = $this->validate();
        $validated['active'] = $this->active;

        $this->environment->update($validated);

        session()->flash('success', 'Entorno actualizado correctamente.');

        return $this->redirect(route('environments.index'), navigate: true);
    }

    public function render()
    {
        return view('livewire.environments.edit', [
            'clients' => Client::orderBy('name')->get(),
            'types' => Type::orderBy('name')->get(),
            'envs' => Environment::ENVIRONMENTS,
        ])->layout('layouts.clean');
    }
}

