<?php

namespace App\Livewire\ScssCdn;

use App\Models\Products\Product;
use App\Models\ScssCdn\ScssCdnBundle;
use Livewire\Component;

class BundleCreate extends Component
{
    public Product $product;
    public string $version = '';
    public ?string $description = null;

    public function mount(Product $product)
    {
        $this->product = $product;
        
        // Generar versión por defecto
        $lastBundle = ScssCdnBundle::where('product_id', $this->product->id)
            ->orderByDesc('version')
            ->first();

        if ($lastBundle) {
            $this->version = $lastBundle->generateNextVersion();
        } else {
            $this->version = date('Ymd') . '00';
        }
    }

    public function save()
    {
        $this->validate([
            'version' => ['required', 'string', 'size:10', 'regex:/^\d{10}$/'],
            'description' => ['nullable', 'string', 'max:1000'],
        ], [
            'version.required' => 'La versión es obligatoria.',
            'version.size' => 'La versión debe tener 10 dígitos (formato YYYYMMDDXX).',
            'version.regex' => 'La versión debe contener solo números.',
        ]);

        // Verificar que la versión no exista
        $exists = ScssCdnBundle::where('product_id', $this->product->id)
            ->where('version', $this->version)
            ->exists();

        if ($exists) {
            $this->addError('version', 'Ya existe un bundle con esta versión para este producto.');
            return;
        }

        try {
            $bundle = ScssCdnBundle::create([
                'product_id' => $this->product->id,
                'version' => $this->version,
                'description' => $this->description,
                'created_by' => auth()->id(),
                'updated_by' => auth()->id(),
            ]);

            session()->flash('success', 'Bundle creado correctamente.');
            return $this->redirect(route('products.scss-cdn.bundle.show', [$this->product, $bundle]), navigate: true);
        } catch (\Exception $e) {
            $this->addError('version', 'Error al crear el bundle: ' . $e->getMessage());
        }
    }

    public function render()
    {
        return view('livewire.scss-cdn.bundle-create', [
            'product' => $this->product,
        ])->layout('layouts.clean');
    }
}
