<?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('deals', function (Blueprint $table) {
            $table->id();
            // Same shape as every other owned table (2026_07_08_000002):
            // nullable column + no DB-level FK — integrity comes from the
            // BelongsToTenant trait and the fail-closed TenantScope.
            $table->unsignedBigInteger('tenant_id')->nullable()->index();
            $table->ulid('uuid')->unique();
            $table->string('name', 150);
            $table->text('description')->nullable();
            // Manual kill switch — a deal that is switched off is never
            // evaluated, whatever its schedule says.
            $table->boolean('is_active')->default(true);
            // Validity window: NULL starts_at = no lower bound, NULL ends_at =
            // no upper bound (same convention as product_bundles).
            $table->timestamp('starts_at')->nullable();
            $table->timestamp('ends_at')->nullable();
            $table->foreignId('discount_type_id')->constrained('discount_types')->restrictOnDelete();
            $table->decimal('discount_value', 12, 2);
            $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('deal_products', function (Blueprint $table) {
            $table->id();
            $table->unsignedBigInteger('tenant_id')->nullable()->index();
            $table->foreignId('deal_id')->constrained('deals')->cascadeOnDelete();
            $table->foreignId('product_id')->constrained('products')->cascadeOnDelete();
            $table->timestamps();
        });
    }

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