<?php

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

return new class extends Migration
{
    /**
     * Run the migrations.
     *
     * Creates the galleries table to store gallery information.
     * Each gallery belongs to an organization and has a type.
     * Tracks creation/updates by users with permission checks.
     *
     * @return void
     */
    public function up(): void
    {
        Schema::create('galleries', function (Blueprint $table) {
            // Primary key
            $table->id();

            // Foreign keys
            $table->foreignId('organization_id')
                ->constrained('organizations')
                ->onDelete('cascade');

            $table->foreignId('gallery_type_id')
                ->constrained('gallery_types')
                ->onDelete('restrict');

            // Gallery details
            $table->string('title', 191);
            $table->text('description')->nullable();

            // Metadata
            $table->integer('image_count')->default(0)->unsigned();
            $table->boolean('is_published')->default(true);
            $table->integer('sort_order')->default(0);

            // Audit trail
            $table->foreignId('created_by')
                ->nullable()
                ->constrained('users')
                ->onDelete('set null');

            $table->foreignId('updated_by')
                ->nullable()
                ->constrained('users')
                ->onDelete('set null');

            // Timestamps and soft deletes
            $table->timestamps();
            $table->softDeletes();

            // Indexes for performance
            $table->index('organization_id');
            $table->index('gallery_type_id');
            $table->index('is_published');
            $table->index('sort_order');
            $table->index('created_by');
        });
    }

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