<?php

declare(strict_types=1);

namespace Database\Seeders;

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

class RolesAndPermissionsSeeder extends Seeder
{
    /**
     * Run the database seeds.
     */
    public function run(): void
    {
        // Reset cached roles and permissions
        app()[PermissionRegistrar::class]->forgetCachedPermissions();

        // Create permissions
        $permissions = [
            'view dashboard',
            'manage users',
            'manage settings',
            'view logs',
            'pos.create',
            'pos.view',
            'inventory.manage',
            'report.view',
            'outlets.manage',
            'products.manage',
        ];

        foreach ($permissions as $permission) {
            Permission::findOrCreate($permission);
        }

        // Create roles and assign existing permissions
        $superAdminRole = Role::findOrCreate('Super Admin');

        $adminRole = Role::findOrCreate('Admin');
        $adminRole->givePermissionTo($permissions);

        $ownerRole = Role::findOrCreate('Owner');
        $ownerRole->givePermissionTo([
            'view dashboard',
            'pos.create',
            'pos.view',
            'inventory.manage',
            'report.view',
            'outlets.manage',
            'products.manage',
            'manage settings',
        ]);

        $kasirRole = Role::findOrCreate('Kasir');
        $kasirRole->givePermissionTo([
            'view dashboard',
            'pos.create',
            'pos.view',
        ]);

        $kitchenRole = Role::findOrCreate('Kitchen');
        $kitchenRole->givePermissionTo([
            'view dashboard',
            'pos.view',
        ]);

        $managerRole = Role::findOrCreate('Manager');
        $managerRole->givePermissionTo(['view dashboard', 'view logs', 'pos.view', 'report.view']);

        $userRole = Role::findOrCreate('User');
        $userRole->givePermissionTo(['view dashboard']);

        $superAdmin = User::firstOrCreate(
            ['email' => 'superadmin@example.com'],
            [
                'name' => 'Super Admin',
                'password' => bcrypt('password'),
            ]
        );
        $superAdmin->syncRoles([$superAdminRole]);

        $admin = User::firstOrCreate(
            ['email' => 'admin@example.com'],
            [
                'name' => 'Admin User',
                'password' => bcrypt('password'),
            ]
        );
        $admin->syncRoles([$adminRole]);

        $regularUser = User::firstOrCreate(
            ['email' => 'user@example.com'],
            [
                'name' => 'Regular User',
                'password' => bcrypt('password'),
            ]
        );
        $regularUser->syncRoles([$userRole]);
    }
}
