<?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::table('artworks', function (Blueprint $table): void {
            $table->foreignId('group_id')
                ->nullable()
                ->after('user_id')
                ->constrained('groups')
                ->nullOnDelete();
            $table->foreignId('uploaded_by_user_id')
                ->nullable()
                ->after('group_id')
                ->constrained('users')
                ->nullOnDelete();
            $table->foreignId('primary_author_user_id')
                ->nullable()
                ->after('uploaded_by_user_id')
                ->constrained('users')
                ->nullOnDelete();

            $table->index(['group_id', 'published_at'], 'artworks_group_published_idx');
        });

        Schema::table('collections', function (Blueprint $table): void {
            $table->foreignId('group_id')
                ->nullable()
                ->after('user_id')
                ->constrained('groups')
                ->nullOnDelete();

            $table->index(['group_id', 'visibility'], 'collections_group_visibility_idx');
        });
    }

    public function down(): void
    {
        Schema::table('collections', function (Blueprint $table): void {
            $table->dropIndex('collections_group_visibility_idx');
            $table->dropConstrainedForeignId('group_id');
        });

        Schema::table('artworks', function (Blueprint $table): void {
            $table->dropIndex('artworks_group_published_idx');
            $table->dropConstrainedForeignId('primary_author_user_id');
            $table->dropConstrainedForeignId('uploaded_by_user_id');
            $table->dropConstrainedForeignId('group_id');
        });
    }
};