<?php

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

return new class extends Migration
{
    public function up(): void
    {
        Schema::table('artworks', function (Blueprint $table): void {
            $table->string('published_as_type', 16)
                ->nullable()
                ->after('primary_author_user_id');
            $table->unsignedBigInteger('published_as_id')
                ->nullable()
                ->after('published_as_type');

            $table->index(['published_as_type', 'published_as_id'], 'artworks_published_as_idx');
        });

        DB::table('artworks')
            ->whereNotNull('group_id')
            ->update([
                'published_as_type' => 'group',
                'published_as_id' => DB::raw('group_id'),
            ]);

        DB::table('artworks')
            ->whereNull('published_as_id')
            ->update([
                'published_as_type' => 'user',
                'published_as_id' => DB::raw('user_id'),
            ]);
    }

    public function down(): void
    {
        Schema::table('artworks', function (Blueprint $table): void {
            $table->dropIndex('artworks_published_as_idx');
            $table->dropColumn(['published_as_type', 'published_as_id']);
        });
    }
};