<?php

namespace Database\Seeders;

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

class RoleAndPermissionSeeder extends Seeder
{
    public function run(): void
    {
        // Reset cached roles and permissions
        app()[\Spatie\Permission\PermissionRegistrar::class]->forgetCachedPermissions();

        // Create permissions
        $permissions = [
            // Admin permissions
            'manage users', 'manage vendors', 'manage products', 'manage orders',
            'manage categories', 'manage brands', 'manage coupons', 'manage settings',
            'view reports', 'manage car makes', 'manage car models',

            // Vendor permissions
            'vendor manage products', 'vendor manage orders', 'vendor view earnings',
            'vendor manage profile', 'vendor view dashboard', 'vendor manage cod orders',

            // Customer permissions
            'place orders', 'write reviews', 'manage wishlist', 'manage addresses',
        ];

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

        // Create roles and assign permissions
        $adminRole = Role::firstOrCreate(['name' => 'admin']);
        $adminRole->syncPermissions(Permission::all());

        $vendorRole = Role::firstOrCreate(['name' => 'vendor']);
        $vendorRole->syncPermissions([
            'vendor manage products', 'vendor manage orders', 'vendor view earnings',
            'vendor manage profile', 'vendor view dashboard', 'vendor manage cod orders',
        ]);

        $customerRole = Role::firstOrCreate(['name' => 'customer']);
        $customerRole->syncPermissions([
            'place orders', 'write reviews', 'manage wishlist', 'manage addresses',
        ]);
    }
}
