<?php

namespace Database\Seeders;

use Illuminate\Database\Seeder;
use Spatie\Permission\Models\Permission;
use Spatie\Permission\Models\Role;
use Spatie\Permission\PermissionRegistrar;

class RoleAndPermissionSeeder extends Seeder
{
    public function run(): void
    {
        app()[PermissionRegistrar::class]->forgetCachedPermissions();

        // ── MENU-LEVEL PERMISSIONS (scope = null) ─────────────────────────────
        $menuPermissions = [
            'view dashboard',
            'view user directory',       'manage user directory',
            'impersonate users',
            'view access rights',        'manage access rights',
            'view health and logs',      'manage health and logs',
            'view system health',        'manage system health',
            'view action history',       'manage action history',
            'view pulse',                'view telescope',          'view api docs',
            'view active sessions',      'manage active sessions',
            'view global settings',      'manage global settings',
            'view maintenance mode',     'manage maintenance mode',
            'view backup and storage',   'manage backup and storage',
            'view mobile settings',      'manage mobile settings',
            'view notification center',  'manage notification center',
            'view ai self-healing',      'manage ai self-healing',
            'view ai log analysis',      'use ai assistant',
        ];

        foreach ($menuPermissions as $name) {
            Permission::firstOrCreate(
                ['name' => $name, 'guard_name' => 'web'],
                ['scope' => null, 'is_active' => true]
            );
        }

        // ── TAB-LEVEL PERMISSIONS [name, scope] ───────────────────────────────
        $tabPermissions = [
            // Global Settings
            ['view global settings:general',           'general'],
            ['manage global settings:general',         'general'],
            ['view global settings:login-security',    'login-security'],
            ['manage global settings:login-security',  'login-security'],
            ['view global settings:password-policy',   'password-policy'],
            ['manage global settings:password-policy', 'password-policy'],
            ['view global settings:social-login',      'social-login'],
            ['manage global settings:social-login',    'social-login'],
            ['view global settings:ip-access',         'ip-access'],
            ['manage global settings:ip-access',       'ip-access'],
            ['view global settings:notifications',     'notifications'],
            ['manage global settings:notifications',   'notifications'],
            ['view global settings:content-legal',     'content-legal'],
            ['manage global settings:content-legal',   'content-legal'],
            ['view global settings:ai-config',         'ai-config'],
            ['manage global settings:ai-config',       'ai-config'],
            ['view global settings:sap-integration',   'sap-integration'],
            ['manage global settings:sap-integration', 'sap-integration'],
            ['view global settings:monitoring',        'monitoring'],
            ['manage global settings:monitoring',      'monitoring'],
            // Mobile Settings
            ['view mobile settings:branding',          'branding'],
            ['manage mobile settings:branding',        'branding'],
            ['view mobile settings:control-center',    'control-center'],
            ['manage mobile settings:control-center',  'control-center'],
            ['view mobile settings:app-updates',       'app-updates'],
            ['manage mobile settings:app-updates',     'app-updates'],
            ['view mobile settings:features',          'features'],
            ['manage mobile settings:features',        'features'],
            ['view mobile settings:security-auth',     'security-auth'],
            ['manage mobile settings:security-auth',   'security-auth'],
            ['view mobile settings:connectivity',      'connectivity'],
            ['manage mobile settings:connectivity',    'connectivity'],
            ['view mobile settings:notifications',     'notifications'],
            ['manage mobile settings:notifications',   'notifications'],
            ['view mobile settings:support-social',    'support-social'],
            ['manage mobile settings:support-social',  'support-social'],
            ['view mobile settings:analytics-system',  'analytics-system'],
            ['manage mobile settings:analytics-system','analytics-system'],
            ['view mobile settings:localization',      'localization'],
            ['manage mobile settings:localization',    'localization'],
            ['view mobile settings:developer',         'developer'],
            ['manage mobile settings:developer',       'developer'],
            // Health & Logs
            ['view health and logs:system-monitor',    'system-monitor'],
            ['manage health and logs:system-monitor',  'system-monitor'],
            ['view health and logs:ai-log-analysis',   'ai-log-analysis'],
            ['view health and logs:error-logs',        'error-logs'],
            ['manage health and logs:error-logs',      'error-logs'],
            ['view health and logs:query-logs',        'query-logs'],
            ['manage health and logs:query-logs',      'query-logs'],
            // Action History
            ['view action history:all',                'all'],
            ['view action history:own',                'own'],
            ['export action history',                  null],
            // Active Sessions
            ['view active sessions:all',               'all'],
            ['view active sessions:own',               'own'],
        ];

        foreach ($tabPermissions as [$name, $scope]) {
            Permission::firstOrCreate(
                ['name' => $name, 'guard_name' => 'web'],
                ['scope' => $scope, 'is_active' => true]
            );
        }

        // ── ROLES ─────────────────────────────────────────────────────────────
        $developer = Role::findOrCreate('Developer', 'web');
        $developer->syncPermissions(Permission::where('guard_name', 'web')->get());

        $globalTabPerms = array_column(
            array_filter($tabPermissions, fn ($p) => str_contains($p[0], 'global settings:')), 0
        );
        $mobileTabPerms = array_column(
            array_filter($tabPermissions, fn ($p) => str_contains($p[0], 'mobile settings:')), 0
        );
        $healthTabPerms = array_column(
            array_filter($tabPermissions, fn ($p) => str_contains($p[0], 'health and logs:')), 0
        );

        $administrator = Role::findOrCreate('Administrator', 'web');
        $administrator->syncPermissions(array_merge([
            'view dashboard',
            'view user directory',      'manage user directory',
            'impersonate users',
            'view mobile settings',     'manage mobile settings',
            'view notification center', 'manage notification center',
            'view global settings',     'manage global settings',
            'view health and logs',     'manage health and logs',
            'view action history',      'manage action history',
            'export action history',
            'view active sessions',     'manage active sessions',
        ], $globalTabPerms, $mobileTabPerms, $healthTabPerms));

        $user = Role::findOrCreate('User', 'web');
        $user->syncPermissions(['view dashboard', 'view notification center']);
    }
}
