<?php

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

return new class extends Migration
{
    /**
     * Run the migrations.
     */
    public function up(): void
    {
        Schema::create('products', function (Blueprint $table) {
            $table->id();

            // Relationships
            $table->unsignedBigInteger('agency_id');
            $table->unsignedBigInteger('product_type_id');

            // Polymorphic relationship
            $table->string('productable_type');
            $table->unsignedBigInteger('productable_id');

            // Common fields
            $table->string('code', 20)->unique();
            $table->string('name');
            $table->string('slug')->unique();
            $table->text('description')->nullable();

            // Pricing
            $table->decimal('base_price', 10, 2)->nullable();
            $table->string('currency', 3)->default('TRY');

            // Status
            $table->boolean('is_active')->default(true);
            $table->boolean('is_featured')->default(false);
            $table->boolean('is_bookable')->default(true);
            $table->timestamp('published_at')->nullable();

            // Analytics
            $table->unsignedInteger('view_count')->default(0);
            $table->unsignedInteger('booking_count')->default(0);

            // Audit
            $table->unsignedBigInteger('created_by')->nullable();
            $table->unsignedBigInteger('updated_by')->nullable();
            $table->timestamps();
            $table->softDeletes();

            // Foreign keys
            $table->foreign('agency_id')->references('id')->on('agencies')->onDelete('cascade');
            $table->foreign('product_type_id')->references('id')->on('product_types')->onDelete('restrict');
            $table->foreign('created_by')->references('id')->on('users')->onDelete('set null');
            $table->foreign('updated_by')->references('id')->on('users')->onDelete('set null');

            // Indexes
            $table->index(['productable_type', 'productable_id']);
            $table->index(['agency_id', 'product_type_id', 'is_active']);
            $table->index(['is_active', 'is_bookable', 'published_at']);
            $table->fullText(['name', 'description']);
        });
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        Schema::dropIfExists('products');
    }
};
