<?php

namespace Database\Seeders;

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

class RolePermissionSeeder extends Seeder
{
    /**
     * Modellere göre tanımlanacak permission grupları.
     *
     * @var list<string>
     */
    private const MODULES = [
        'category',
        'course',
        'schedule',
        'announcement',
        'hero-slide',
        'lead',
        'menu',
        'comment',
        'faq',
        'guide-card',
        'setting',
        'page',
        'user',
        'role',
    ];

    /**
     * Her modül için oluşturulacak CRUD aksiyonlar.
     *
     * @var list<string>
     */
    private const ACTIONS = ['view', 'create', 'update', 'delete'];

    /**
     * Editor rolüne verilmeyecek aksiyonlar.
     *
     * @var list<string>
     */
    private const EDITOR_EXCLUDED_ACTIONS = ['delete'];

    /**
     * Run the database seeds.
     */
    public function run(): void
    {
        app()[PermissionRegistrar::class]->forgetCachedPermissions();

        $allPermissions = [];
        $editorPermissions = [];

        foreach (self::MODULES as $module) {
            foreach (self::ACTIONS as $action) {
                $permissionName = "{$action}-{$module}";
                Permission::firstOrCreate(['name' => $permissionName, 'guard_name' => 'web']);
                $allPermissions[] = $permissionName;

                if (! in_array($action, self::EDITOR_EXCLUDED_ACTIONS)) {
                    $editorPermissions[] = $permissionName;
                }
            }
        }

        // super-admin: tüm yetkiler
        $superAdmin = Role::firstOrCreate(['name' => 'super-admin', 'guard_name' => 'web']);
        $superAdmin->syncPermissions($allPermissions);

        // editor: silme hariç tüm yetkiler
        $editor = Role::firstOrCreate(['name' => 'editor', 'guard_name' => 'web']);
        $editor->syncPermissions($editorPermissions);
    }
}
