<?php

namespace Database\Seeders;

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

/**
 * SiteManagementPermissionSeeder
 *
 * Seeds all permissions for the Site Management module (Topbar Notifications
 * and Email Subscribers) and assigns them to Super Manager and Manager roles.
 *
 * Requirements: 5.1, 5.2, 5.3, 9.4, 9.5, 9.6
 */
class SiteManagementPermissionSeeder extends Seeder
{
    public function run(): void
    {
        // Reset cached roles and permissions
        app()[\Spatie\Permission\PermissionRegistrar::class]->forgetCachedPermissions();

        // ----------------------------------------------------------------
        // Topbar Notification permissions (Requirements 5.1)
        // ----------------------------------------------------------------
        $topbarPermissions = [
            'view topbar notifications',
            'create topbar notifications',
            'edit topbar notifications',
            'delete topbar notifications',
        ];

        // ----------------------------------------------------------------
        // Email Subscriber permissions (Requirements 9.4)
        // ----------------------------------------------------------------
        $subscriberPermissions = [
            'view email subscribers',
            'export email subscribers',
            'manage email subscribers',
        ];

        $allPermissions = array_merge($topbarPermissions, $subscriberPermissions);

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

        $this->command->info('Created ' . count($allPermissions) . ' site management permissions.');

        // ----------------------------------------------------------------
        // Assign all 7 permissions to Super Manager (Requirements 5.2, 9.5)
        // ----------------------------------------------------------------
        $superManager = Role::where('name', 'Super Manager')->first();
        if ($superManager) {
            $superManager->givePermissionTo($allPermissions);
            $this->command->info('Super Manager: all site management permissions assigned.');
        }

        // ----------------------------------------------------------------
        // Assign all 7 permissions to Manager (Requirements 5.3, 9.6)
        // ----------------------------------------------------------------
        $manager = Role::where('name', 'Manager')->first();
        if ($manager) {
            $manager->givePermissionTo($allPermissions);
            $this->command->info('Manager: all site management permissions assigned.');
        }

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

        $this->command->info('Site Management permissions seeded successfully!');
    }
}
