<?php

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

/**
 * Keranjang belanja disimpan di database (KOD-01 diputuskan: database session).
 *
 * DESAIN:
 * - user_id terisi jika sudah login.
 * - session_id terisi jika guest.
 * - Saat guest login, cart di-merge: session_id -> user_id.
 * - Constraint unique: satu produk hanya satu baris per user/session.
 *   Qty tambah dilakukan dengan increment, bukan insert baru.
 *
 * CATATAN:
 * - Kedua unique constraint dibuat terpisah karena MySQL tidak mendukung
 *   conditional unique index dengan sintaks standar.
 * - Validasi "hanya satu yang terisi" dilakukan di aplikasi level.
 */
return new class extends Migration
{
    public function up(): void
    {
        Schema::create('carts', function (Blueprint $table) {
            $table->id();

            $table->foreignId('user_id')
                ->nullable()
                ->constrained('users')
                ->cascadeOnDelete(); // hapus cart jika user dihapus

            $table->string('session_id', 100)->nullable()->index();

            $table->foreignId('product_id')
                ->constrained('products')
                ->cascadeOnDelete(); // hapus cart item jika produk dihapus

            $table->unsignedSmallInteger('quantity')->default(1);
            $table->timestamps();

            // Satu produk per user
            $table->unique(['user_id', 'product_id'], 'cart_user_product_unique');
        });
    }

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