<?php

namespace Database\Seeders;

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

class AddWorkflowPermissionsSeeder extends Seeder
{
    public function run(): void
    {
        $names = [
            'view workflows',
            'create workflows',
            'edit workflows',
            'delete workflows',
            'execute workflows',
            'My Workflows',
        ];

        // Create permissions and collect model instances
        $permMap = [];
        foreach ($names as $name) {
            $permMap[strtolower($name)] = Permission::firstOrCreate(['name' => $name, 'guard_name' => 'web']);
        }

        // Give Super Admin all workflow permissions
        $superAdmin = Role::where('name', 'Super Admin')->first();
        if ($superAdmin) {
            $superAdmin->givePermissionTo(array_values($permMap));
        }

        // Give Admin view/create/edit/execute/my workflows
        $admin = Role::where('name', 'Admin')->first();
        if ($admin) {
            $admin->givePermissionTo([
                $permMap['view workflows'],
                $permMap['create workflows'],
                $permMap['edit workflows'],
                $permMap['execute workflows'],
                $permMap['my workflows'],
            ]); // my workflows key is lowercased
        }

        // Give User view + my workflows
        $user = Role::where('name', 'User')->first();
        if ($user) {
            $user->givePermissionTo([
                $permMap['view workflows'],
                $permMap['my workflows'],
            ]); // my workflows key is lowercased
        }

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