<?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
{
    public function run(): void
    {
        // Reset cache Spatie sebelum dan sesudah seeder
        app()[PermissionRegistrar::class]->forgetCachedPermissions();

        // ── Semua permission ──────────────────────────────────────────────
        $permissions = [
            'order.view', 'order.update-status', 'order.cancel', 'order.assign',
            'payment.verify', 'payment.reject',
            'product.view', 'product.create', 'product.edit', 'product.delete',
            'category.view', 'category.create', 'category.edit', 'category.delete',
            'partner.view', 'partner.create', 'partner.edit', 'partner.delete',
            'banner.view', 'banner.create', 'banner.edit', 'banner.delete',
            'voucher.view', 'voucher.create', 'voucher.edit', 'voucher.delete',
            'delivery.view', 'delivery.create', 'delivery.edit', 'delivery.delete',
            'customer.view', 'customer.deactivate',
            'report.view', 'report.export',
            'user.view', 'user.create', 'user.edit', 'user.delete',
            'role.manage',
            'setting.manage',
            'audit.view',
        ];

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

        // ── Role: super_admin — full access ───────────────────────────────
        $superAdmin = Role::firstOrCreate([
            'name'       => 'super_admin',
            'guard_name' => 'web',
        ]);
        $superAdmin->syncPermissions(Permission::where('guard_name', 'web')->get());

        // ── Role: admin — operasional ─────────────────────────────────────
        $admin = Role::firstOrCreate([
            'name'       => 'admin',
            'guard_name' => 'web',
        ]);
        $admin->syncPermissions([
            'order.view', 'order.update-status',
            'payment.verify', 'payment.reject',
            'product.view', 'product.create', 'product.edit',
            'category.view',
            'partner.view',
            'banner.view',
            'voucher.view',
            'delivery.view',
            'customer.view',
            'report.view',
        ]);

        // ── Role: customer — tanpa permission Spatie ───────────────────────
        Role::firstOrCreate([
            'name'       => 'customer',
            'guard_name' => 'web',
        ]);

        // Reset cache setelah selesai
        app()[PermissionRegistrar::class]->forgetCachedPermissions();
    }
}
