<?php

namespace App\Livewire\Environments\Components;

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

class EnvironmentForm 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(?int $client_id = null, array $initialData = [])
    {
        $this->client_id = $client_id;
        $this->env = 'local';

        // Pre-llenar con datos iniciales si se proporcionan
        if (!empty($initialData)) {
            $this->name = $initialData['name'] ?? '';
            $this->domain = $initialData['domain'] ?? '';
            $this->description = $initialData['description'] ?? null;
            $this->version = $initialData['version'] ?? '';
            $this->env = $initialData['env'] ?? 'local';
            $this->type_id = $initialData['type_id'] ?? null;
            $this->active = $initialData['active'] ?? true;
        }
    }

    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|in:local,develop,pre,pro',
            'client_id' => 'required|exists:clients,id',
            'type_id' => 'nullable|exists:types,id',
            'active' => 'sometimes|accepted',
        ];
    }

    public function save()
    {
        $validated = $this->validate();
        $validated['active'] = $this->active;

        $environment = Environment::create($validated);

        // Emitir evento con los datos del entorno creado
        $this->dispatch('environmentSaved', [
            'environment' => $environment,
            'environment_id' => $environment->id,
        ]);

        return $environment;
    }

    public function render()
    {
        return view('livewire.environments.components.environment-form', [
            'types' => Type::orderBy('name')->get(),
            'envs' => Environment::ENVIRONMENTS,
        ]);
    }
}

