<?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('groups', function (Blueprint $table): void {
            if (! Schema::hasColumn('groups', 'status')) {
                $table->string('status', 24)->default('active')->after('visibility');
            }

            if (! Schema::hasColumn('groups', 'membership_policy')) {
                $table->string('membership_policy', 32)->default('invite_only')->after('status');
            }

            if (! Schema::hasColumn('groups', 'type')) {
                $table->string('type', 80)->nullable()->after('bio');
            }

            if (! Schema::hasColumn('groups', 'founded_at')) {
                $table->timestamp('founded_at')->nullable()->after('owner_user_id');
            }

            if (! Schema::hasColumn('groups', 'featured_artwork_id')) {
                $table->foreignId('featured_artwork_id')->nullable()->after('owner_user_id')->constrained('artworks')->nullOnDelete();
            }

            if (! Schema::hasColumn('groups', 'is_verified')) {
                $table->boolean('is_verified')->default(false)->after('featured_artwork_id');
            }

            if (! Schema::hasColumn('groups', 'deleted_at')) {
                $table->softDeletes();
            }
        });

        if (DB::connection()->getDriverName() === 'mysql') {
            DB::statement("ALTER TABLE `groups` MODIFY `visibility` ENUM('public','private','unlisted') NOT NULL DEFAULT 'public'");
        }
    }

    public function down(): void
    {
        if (DB::connection()->getDriverName() === 'mysql') {
            DB::statement("ALTER TABLE `groups` MODIFY `visibility` ENUM('public','private') NOT NULL DEFAULT 'public'");
        }

        Schema::table('groups', function (Blueprint $table): void {
            if (Schema::hasColumn('groups', 'deleted_at')) {
                $table->dropSoftDeletes();
            }

            if (Schema::hasColumn('groups', 'is_verified')) {
                $table->dropColumn('is_verified');
            }

            if (Schema::hasColumn('groups', 'featured_artwork_id')) {
                $table->dropConstrainedForeignId('featured_artwork_id');
            }

            if (Schema::hasColumn('groups', 'founded_at')) {
                $table->dropColumn('founded_at');
            }

            if (Schema::hasColumn('groups', 'type')) {
                $table->dropColumn('type');
            }

            if (Schema::hasColumn('groups', 'membership_policy')) {
                $table->dropColumn('membership_policy');
            }

            if (Schema::hasColumn('groups', 'status')) {
                $table->dropColumn('status');
            }
        });
    }
};