<?php

namespace App\Livewire\Environments;

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

class Create extends Component
{
    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()
    {
        $this->env = 'local';
    }

    protected function rules()
    {
        return [
            'name' => 'required|string|max:255',
            'domain' => 'required|string|max:255|unique:environments,domain',
            '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 save()
    {
        $this->authorize('admin.environments.create');
        
        $validated = $this->validate();
        $validated['active'] = $this->active;

        Environment::create($validated);

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

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

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

