<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    public function up(): void
    {
        Schema::create('manychat_carritos', function (Blueprint $table): void {
            $table->id();
            $table->unsignedBigInteger('empresa_id');
            $table->string('session_id', 160);
            $table->string('cliente_nombre', 160)->nullable();
            $table->string('telefono', 30)->nullable();
            $table->text('direccion')->nullable();
            $table->text('observaciones')->nullable();
            $table->decimal('total', 14, 2)->default(0);
            $table->enum('estado', ['activo', 'confirmado', 'cancelado'])->default('activo');
            $table->unsignedBigInteger('pedido_id')->nullable();
            $table->timestamp('last_activity_at')->nullable();
            $table->timestamp('confirmed_at')->nullable();
            $table->timestamps();

            $table->index(['empresa_id', 'session_id']);
            $table->index(['empresa_id', 'estado']);
            $table->foreign('empresa_id')->references('id')->on('empresas')->onDelete('cascade');
            $table->foreign('pedido_id')->references('id')->on('manychat_pedidos')->nullOnDelete();
        });

        Schema::create('manychat_carrito_items', function (Blueprint $table): void {
            $table->id();
            $table->unsignedBigInteger('carrito_id');
            $table->unsignedBigInteger('producto_id');
            $table->string('producto_nombre', 200);
            $table->decimal('precio_unitario', 14, 2);
            $table->decimal('cantidad', 10, 2);
            $table->decimal('subtotal', 14, 2);
            $table->timestamps();

            $table->unique(['carrito_id', 'producto_id']);
            $table->foreign('carrito_id')->references('id')->on('manychat_carritos')->onDelete('cascade');
            $table->foreign('producto_id')->references('id')->on('productos')->onDelete('restrict');
        });
    }

    public function down(): void
    {
        Schema::dropIfExists('manychat_carrito_items');
        Schema::dropIfExists('manychat_carritos');
    }
};
