<?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('collections', function (Blueprint $table): void {
            $table->id();
            $table->foreignId('user_id')
                ->constrained('users')
                ->cascadeOnDelete();
            $table->string('title', 120);
            $table->string('slug', 140);
            $table->text('description')->nullable();
            $table->foreignId('cover_artwork_id')
                ->nullable()
                ->constrained('artworks')
                ->nullOnDelete();
            $table->enum('visibility', ['public', 'unlisted', 'private'])->default('public');
            $table->enum('sort_mode', ['manual', 'newest', 'oldest', 'popular'])->default('manual');
            $table->unsignedInteger('artworks_count')->default(0);
            $table->boolean('is_featured')->default(false);
            $table->timestamps();
            $table->softDeletes();

            $table->unique(['user_id', 'slug'], 'collections_user_slug_unique');
            $table->index('user_id');
            $table->index('visibility');
            $table->index('created_at');
        });

        Schema::create('collection_artwork', function (Blueprint $table): void {
            $table->id();
            $table->foreignId('collection_id')
                ->constrained('collections')
                ->cascadeOnDelete();
            $table->foreignId('artwork_id')
                ->constrained('artworks')
                ->cascadeOnDelete();
            $table->unsignedInteger('order_num')->default(0);
            $table->timestamps();

            $table->unique(['collection_id', 'artwork_id'], 'collection_artwork_unique');
            $table->index(['collection_id', 'order_num'], 'collection_artwork_order_idx');
            $table->index('artwork_id');
        });
    }

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