<?php

namespace Database\Seeders;

use App\Models\Admin;
use App\Models\Permission;
use App\Models\Role;
use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\Hash;

class AdminAuthorizationSeeder extends Seeder
{
    public function run(): void
    {
        $role = Role::query()->updateOrCreate(
            ['name' => 'super-admin'],
            ['display_name' => 'Super Administrator', 'description' => 'Unrestricted platform administration.', 'is_system' => true],
        );

        $permission = Permission::query()->updateOrCreate(
            ['name' => 'dashboard.view'],
            ['display_name' => 'View dashboard', 'module' => 'dashboard'],
        );
        $role->permissions()->syncWithoutDetaching([$permission->getKey()]);

        $email = config('app.bootstrap_admin_email');
        $password = config('app.bootstrap_admin_password');
        if (app()->isLocal() && filled($email) && filled($password)) {
            $admin = Admin::query()->updateOrCreate(
                ['email' => $email],
                ['name' => config('app.bootstrap_admin_name'), 'password' => Hash::make($password), 'is_active' => true, 'email_verified_at' => now()],
            );
            $admin->roles()->syncWithoutDetaching([$role->getKey()]);
        }
    }
}
