<?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('users', function (Blueprint $table) {
            // superadmin = SaaS owner (full access + manage admins)
            // admin      = team member with admin panel access
            // user       = company / client user (user dashboard only)
            $table->enum('role', ['superadmin', 'admin', 'user'])
                  ->default('user')
                  ->after('remember_token');
        });

        // Auto-promote the first-ever user (lowest id) to superadmin — they registered the platform.
        // All others default to 'user'; admins must be promoted manually or via seeder.
        DB::statement("
            UPDATE users
            SET role = 'superadmin'
            WHERE id = (SELECT min_id FROM (SELECT MIN(id) AS min_id FROM users) AS sub)
        ");
    }

    public function down(): void
    {
        Schema::table('users', function (Blueprint $table) {
            $table->dropColumn('role');
        });
    }
};
