<?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
    {
        // Prevent duplicate creation: if the users table already exists (it is
        // created by the core 0001_01_01_000000_create_users_table.php), do not
        // recreate it. Instead, only add any missing columns expected by this
        // project (username, role) if they don't already exist.
        if (!Schema::hasTable('users')) {
            Schema::create('users', function (Blueprint $table) {
                $table->id();
                $table->string('name');
                $table->string('username')->nullable()->unique();
                $table->string('email')->unique();
                $table->timestamp('email_verified_at')->nullable();
                $table->string('password');
                $table->string('role')->default('pegawai'); // 'admin' or 'pegawai'
                $table->rememberToken();
                $table->timestamps();
            });
        } else {
            Schema::table('users', function (Blueprint $table) {
                if (!Schema::hasColumn('users', 'username')) {
                    $table->string('username')->nullable()->unique()->after('name');
                }
                if (!Schema::hasColumn('users', 'role')) {
                    $table->string('role')->default('pegawai')->after('password');
                }
            });
        }
    }

    public function down(): void
    {
        // Be conservative on down: if this migration created the table, drop it.
        // Otherwise, only remove the columns we may have added.
        if (Schema::hasTable('users')) {
            // If the table existed before this migration, it will also be
            // referenced by other migrations, so avoid dropping the table.
            if (Schema::hasColumn('users', 'username')) {
                Schema::table('users', function (Blueprint $table) {
                    $table->dropColumn('username');
                });
            }
            if (Schema::hasColumn('users', 'role')) {
                Schema::table('users', function (Blueprint $table) {
                    $table->dropColumn('role');
                });
            }
        }
    }
};
