<?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('product_bundles', function (Blueprint $table) {
            $table->id();
            $table->ulid('uuid')->unique();
            $table->string('name', 150);
            $table->string('sku', 60)->unique();
            $table->text('description')->nullable();
            $table->decimal('sale_price', 12, 2);
            $table->string('image_url', 500)->nullable();
            // NULL = available at all branches. Deliberately no BranchScoped
            // trait here — that scope treats an unresolved/NULL branch as "no
            // rows", which is the opposite of what an "all branches" bundle needs.
            $table->foreignId('branch_id')->nullable()->constrained('warehouses')->nullOnDelete();
            $table->boolean('is_active')->default(true);
            $table->date('starts_at')->nullable();
            $table->date('ends_at')->nullable();
            $table->foreignId('created_by')->nullable()->constrained('users')->nullOnDelete();
            $table->foreignId('updated_by')->nullable()->constrained('users')->nullOnDelete();
            $table->foreignId('deleted_by')->nullable()->constrained('users')->nullOnDelete();
            $table->timestamps();
            $table->softDeletes();
        });

        Schema::create('bundle_items', function (Blueprint $table) {
            $table->id();
            $table->ulid('uuid')->unique();
            $table->foreignId('bundle_id')->constrained('product_bundles')->cascadeOnDelete();
            $table->foreignId('product_id')->constrained('products')->restrictOnDelete();
            $table->unsignedBigInteger('product_variant_id')->nullable();
            $table->decimal('quantity', 12, 4);
            $table->foreignId('unit_id')->nullable()->constrained('unit_of_measures')->nullOnDelete();
            $table->foreignId('created_by')->nullable()->constrained('users')->nullOnDelete();
            $table->timestamps();
        });
    }

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