<?php

namespace Database\Seeders;

use Illuminate\Database\Seeder;
use App\Models\User;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;
use Spatie\Permission\Models\Role;
use Spatie\Permission\Models\Permission;
use Spatie\Permission\PermissionRegistrar;

class UserRolePermissionSeeder extends Seeder
{
    public function run(): void
    {
        $guard = 'web';

        DB::statement('SET FOREIGN_KEY_CHECKS=0;');

        DB::table('role_has_permissions')->truncate();
        DB::table('model_has_permissions')->truncate();
        DB::table('model_has_roles')->truncate();

        Permission::truncate();
        Role::truncate();
        User::truncate();

        DB::statement('SET FOREIGN_KEY_CHECKS=1;');

        app()[PermissionRegistrar::class]->forgetCachedPermissions();

        // -------------------------
        // CREATE ONLY SUPER ADMIN ROLE
        // -------------------------
        $superAdmin = Role::firstOrCreate([
            'name' => 'super admin',
            'guard_name' => $guard,
        ]);

        // -------------------------
        // CREATE PERMISSIONS
        // -------------------------
        $permissions = [
            'view dashboard',
            'manage users',
            'manage roles',
            'manage permissions',
            'manage general settings',
        ];

        foreach ($permissions as $permission) {
            Permission::firstOrCreate([
                'name' => $permission,
                'guard_name' => $guard,
            ]);
        }

        // Super Admin gets all permissions
        $superAdmin->syncPermissions(Permission::all());

        // -------------------------
        // CREATE SUPER ADMIN USER
        // -------------------------
        User::create([
            'name' => 'Super Admin',
            'email' => 'superadmin@gmail.com',
            'password' => Hash::make('12345678'),
        ])->assignRole('super admin');

        $this->command->info('Seeded: super admin role, permissions, and user successfully!');
    }
}