<?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
    {
        if (Schema::getConnection()->getDriverName() === 'sqlite') {
            // Rebuild role_user without surrogate id
            if (Schema::hasTable('role_user')) {
                Schema::create('role_user_temp', function (Blueprint $table) {
                    $table->foreignId('role_id');
                    $table->foreignId('user_id');
                    $table->timestamps();
                });
                // Copy distinct rows
                try {
                    \DB::statement('INSERT INTO role_user_temp (role_id, user_id, created_at, updated_at) SELECT role_id, user_id, created_at, updated_at FROM role_user GROUP BY role_id, user_id');
                } catch (Throwable $e) { /* ignore */
                }
                Schema::drop('role_user');
                Schema::rename('role_user_temp', 'role_user');
                // Add composite primary key via raw SQL
                try {
                    \DB::statement('CREATE UNIQUE INDEX role_user_role_user_unique ON role_user(role_id, user_id)');
                } catch (Throwable $e) { /* ignore */
                }
            }
            if (Schema::hasTable('permission_role')) {
                Schema::create('permission_role_temp', function (Blueprint $table) {
                    $table->foreignId('permission_id');
                    $table->foreignId('role_id');
                    $table->timestamps();
                });
                try {
                    \DB::statement('INSERT INTO permission_role_temp (permission_id, role_id, created_at, updated_at) SELECT permission_id, role_id, created_at, updated_at FROM permission_role GROUP BY permission_id, role_id');
                } catch (Throwable $e) { /* ignore */
                }
                Schema::drop('permission_role');
                Schema::rename('permission_role_temp', 'permission_role');
                try {
                    \DB::statement('CREATE UNIQUE INDEX permission_role_permission_role_unique ON permission_role(permission_id, role_id)');
                } catch (Throwable $e) { /* ignore */
                }
            }

            return; // sqlite path done
        }
        // role_user
        if (Schema::hasColumn('role_user', 'id')) {
            // Drop id column; Postgres requires dropping pk constraint implicitly named maybe 'role_user_pkey'
            // Attempt raw drop primary if exists
            try {
                \DB::statement('ALTER TABLE role_user DROP CONSTRAINT role_user_pkey');
            } catch (Throwable $e) { /* ignore */
            }
            Schema::table('role_user', function (Blueprint $table) {
                $table->dropColumn('id');
            });
        }
        // Add composite primary key if not present
        try {
            \DB::statement('ALTER TABLE role_user ADD PRIMARY KEY (role_id, user_id)');
        } catch (Throwable $e) { /* ignore */
        }

        // permission_role
        if (Schema::hasColumn('permission_role', 'id')) {
            try {
                \DB::statement('ALTER TABLE permission_role DROP CONSTRAINT permission_role_pkey');
            } catch (Throwable $e) { /* ignore */
            }
            Schema::table('permission_role', function (Blueprint $table) {
                $table->dropColumn('id');
            });
        }
        try {
            \DB::statement('ALTER TABLE permission_role ADD PRIMARY KEY (permission_id, role_id)');
        } catch (Throwable $e) { /* ignore */
        }
    }

    public function down(): void
    {
        if (Schema::getConnection()->getDriverName() === 'sqlite') {
            // Recreate tables with id column again (best-effort)
            if (Schema::hasTable('role_user')) {
                Schema::create('role_user_orig', function (Blueprint $table) {
                    $table->id();
                    $table->foreignId('role_id');
                    $table->foreignId('user_id');
                    $table->timestamps();
                });
                try {
                    \DB::statement('INSERT INTO role_user_orig (role_id, user_id, created_at, updated_at) SELECT role_id, user_id, created_at, updated_at FROM role_user');
                } catch (Throwable $e) { /* ignore */
                }
                Schema::drop('role_user');
                Schema::rename('role_user_orig', 'role_user');
                try {
                    \DB::statement('CREATE UNIQUE INDEX role_user_role_user_unique ON role_user(role_id, user_id)');
                } catch (Throwable $e) { /* ignore */
                }
            }
            if (Schema::hasTable('permission_role')) {
                Schema::create('permission_role_orig', function (Blueprint $table) {
                    $table->id();
                    $table->foreignId('permission_id');
                    $table->foreignId('role_id');
                    $table->timestamps();
                });
                try {
                    \DB::statement('INSERT INTO permission_role_orig (permission_id, role_id, created_at, updated_at) SELECT permission_id, role_id, created_at, updated_at FROM permission_role');
                } catch (Throwable $e) { /* ignore */
                }
                Schema::drop('permission_role');
                Schema::rename('permission_role_orig', 'permission_role');
                try {
                    \DB::statement('CREATE UNIQUE INDEX permission_role_permission_role_unique ON permission_role(permission_id, role_id)');
                } catch (Throwable $e) { /* ignore */
                }
            }

            return;
        }
        // Re-add id columns (simple auto increment) and drop composite PKs
        Schema::table('role_user', function (Blueprint $table) {
            try {
                $table->dropPrimary();
            } catch (Throwable $e) { /* ignore */
            }
            if (! Schema::hasColumn('role_user', 'id')) {
                $table->id()->first();
            }
            $table->unique(['role_id', 'user_id']);
        });
        Schema::table('permission_role', function (Blueprint $table) {
            try {
                $table->dropPrimary();
            } catch (Throwable $e) { /* ignore */
            }
            if (! Schema::hasColumn('permission_role', 'id')) {
                $table->id()->first();
            }
            $table->unique(['permission_id', 'role_id']);
        });
    }
};
