<?php

namespace Database\Seeders;

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

class AuthModulePermissionSeeder extends Seeder
{
    /**
     * Run the database seeds.
     */
    public function run(): void
    {
        // Reset cached roles and permissions
        app()[\Spatie\Permission\PermissionRegistrar::class]->forgetCachedPermissions();

        // ========================================================================
        // CREATE PERMISSIONS
        // ========================================================================

        $permissionTypes = ['view', 'create', 'edit', 'delete', 'approve', 'deactivate', 'manage'];
        $resources = [
            'users',
            'roles',
            'permissions',
            'dashboards',
            'otp settings',
            'sessions',
            'login attempts',
            'user profiles',
            'system settings',
        ];

        $permissions = [];

        foreach ($resources as $resource) {
            foreach ($permissionTypes as $type) {
                $permissionName = "{$type} {$resource}";
                $permission = Permission::firstOrCreate(
                    ['name' => $permissionName, 'guard_name' => 'web']
                );
                $permissions[] = $permission;
            }
        }

        // Additional specific permissions
        $specificPermissions = [
            'view statistics',
            'export users',
            'import users',
            'manage two-factor',
            'manage social accounts',
            'resend verification email',
            'reset user password',
            'view audit logs',
            'manage themes',
            'access admin panel',
        ];

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

        $this->command->info('Permissions created: ' . count($permissions));

        // ========================================================================
        // CREATE ROLES AND ASSIGN PERMISSIONS
        // ========================================================================

        $rolesConfig = [
            'Super Manager' => [
                'theme' => 'dark',
                // Super Manager gets all permissions — assigned after the loop via givePermissionTo(Permission::all())
                'permissions' => [],
            ],
            'Manager' => [
                'theme' => 'blue',
                'permissions' => [
                    'view users',
                    'create users',
                    'edit users',
                    'delete users',
                    'view roles',
                    'view permissions',
                    'view dashboards',
                    'view statistics',
                    'view user profiles',
                    'edit user profiles',
                    'resend verification email',
                    'reset user password',
                    'view login attempts',
                ],
            ],
            'Members' => [
                'theme' => 'default',
                'permissions' => [
                    'view dashboards',
                    'view user profiles',
                    'edit user profiles',
                ],
            ],
            'Trainers' => [
                'theme' => 'green',
                'permissions' => [
                    'view dashboards',
                    'view user profiles',
                    'edit user profiles',
                ],
            ],
            'Trainees' => [
                'theme' => 'light',
                'permissions' => [
                    'view dashboards',
                    'view user profiles',
                    'edit user profiles',
                ],
            ],
            'Mentor' => [
                'theme' => 'purple',
                'permissions' => [
                    'view dashboards',
                    'view user profiles',
                    'edit user profiles',
                ],
            ],
            'Mentee' => [
                'theme' => 'light',
                'permissions' => [
                    'view dashboards',
                    'view user profiles',
                    'edit user profiles',
                ],
            ],
            'Partners' => [
                'theme' => 'blue',
                'permissions' => [
                    'view dashboards',
                    'view user profiles',
                    'edit user profiles',
                ],
            ],
            'Contributor' => [
                'theme' => 'green',
                'permissions' => [
                    'view dashboards',
                    'view user profiles',
                    'edit user profiles',
                ],
            ],
            'Health Marketor' => [
                'theme' => 'red',
                'permissions' => [
                    'view dashboards',
                    'view user profiles',
                    'edit user profiles',
                    'view statistics',
                ],
            ],
        ];

        foreach ($rolesConfig as $roleName => $config) {
            $role = Role::firstOrCreate(
                ['name' => $roleName, 'guard_name' => 'web']
            );

            // Update theme if roles table has theme column
            if (\Illuminate\Support\Facades\Schema::hasColumn('roles', 'theme')) {
                $role->update(['theme' => $config['theme']]);
            }

            // Use givePermissionTo (additive) instead of syncPermissions to avoid
            // overwriting permissions assigned by other seeders in the pipeline.
            if (!empty($config['permissions'])) {
                $role->givePermissionTo($config['permissions']);
            }

            $this->command->info("Role '{$roleName}' created/updated with " . count($config['permissions']) . " permissions.");
        }

        // Super Manager gets ALL permissions that exist at this point (additive)
        $superManagerRole = Role::where('name', 'Super Manager')->first();
        if ($superManagerRole) {
            $superManagerRole->givePermissionTo(Permission::all());
            $this->command->info("Super Manager: all current permissions assigned.");
        }

        // ========================================================================
        // CREATE DEFAULT SUPER MANAGER USER
        // ========================================================================

        $superManager = User::firstOrCreate(
            ['email' => 'admin@sshia.com'],
            [
                'name' => 'Super Admin',
                'username' => 'superadmin',
                'password' => Hash::make('password'),
                'email_verified_at' => now(),
                'is_active' => true,
            ]
        );

        $superManager->assignRole('Super Manager');

        $this->command->info('');
        $this->command->info('===========================================');
        $this->command->info('  AUTH MODULE PERMISSIONS SEEDED!');
        $this->command->info('===========================================');
        $this->command->info('');
        $this->command->info('Default Super Manager Credentials:');
        $this->command->info('  Email: admin@sshia.com');
        $this->command->info('  Password: password');
        $this->command->info('');
        $this->command->info('IMPORTANT: Change the default password immediately!');
        $this->command->info('===========================================');

        // Clear permission cache after seeding
        app()[\Spatie\Permission\PermissionRegistrar::class]->forgetCachedPermissions();
    }
}
