<?php

namespace Database\Seeders;

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

/**
 * WhatWeDoImagePermissionSeeder
 *
 * Seeds the `manage what we do images` permission and assigns it to
 * the Super Manager and Manager roles.
 *
 * Requirements: 9.1, 9.2, 9.3, 9.4
 */
class WhatWeDoImagePermissionSeeder extends Seeder
{
    public function run(): void
    {
        // Reset cached roles and permissions before seeding
        app()[\Spatie\Permission\PermissionRegistrar::class]->forgetCachedPermissions();

        // Create the permission idempotently (Requirement 9.1, 9.4)
        Permission::firstOrCreate(
            ['name' => 'manage what we do images'],
            ['guard_name' => 'web']
        );

        $this->command->info('Created permission: manage what we do images');

        // Assign to Super Manager (Requirement 9.2)
        $superManager = Role::where('name', 'Super Manager')->first();
        if ($superManager) {
            $superManager->givePermissionTo('manage what we do images');
            $this->command->info('Super Manager: manage what we do images permission assigned.');
        }

        // Assign to Manager (Requirement 9.3)
        $manager = Role::where('name', 'Manager')->first();
        if ($manager) {
            $manager->givePermissionTo('manage what we do images');
            $this->command->info('Manager: manage what we do images permission assigned.');
        }

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

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