<?php

namespace Modules\SystemCore\Database\Seeders;

use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\DB;
use Spatie\Permission\Models\Permission;
use Spatie\Permission\Models\Role;

class SystemCorePermissionSeeder extends Seeder
{
    /**
     * SystemCore module permissions organized by category
     *
     * @var array<string, list<array{name: string, description: string}>>
     */
    protected array $permissions = [];

    /**
     * Run the database seeds.
     */
    public function run(): void
    {
        // Reset cached roles and permissions
        app(\Spatie\Permission\PermissionRegistrar::class)->forgetCachedPermissions();

        DB::beginTransaction();

        try {
            $this->definePermissions();
            $this->createPermissions();
            $this->updateRolePermissions();

            DB::commit();
            $this->command->info('SystemCore permissions seeded successfully!');
        } catch (\Exception $e) {
            DB::rollBack();
            $this->command->error('Error seeding SystemCore permissions: '.$e->getMessage());
        }
    }

    /**
     * Define all SystemCore permissions by category
     */
    protected function definePermissions(): void
    {
        $this->permissions = [
            // Product Management
            'Product Management' => [
                ['name' => 'systemcore.view-products', 'description' => 'View products'],
                ['name' => 'systemcore.create-product', 'description' => 'Create new products'],
                ['name' => 'systemcore.edit-product', 'description' => 'Edit products'],
                ['name' => 'systemcore.delete-product', 'description' => 'Delete products'],
            ],

            // Category Management
            'Category Management' => [
                ['name' => 'systemcore.view-categories', 'description' => 'View product categories'],
                ['name' => 'systemcore.create-category', 'description' => 'Create new product categories'],
                ['name' => 'systemcore.edit-category', 'description' => 'Edit product categories'],
                ['name' => 'systemcore.delete-category', 'description' => 'Delete product categories'],
            ],
        ];
    }

    /**
     * Create all permissions in the database
     */
    protected function createPermissions(): void
    {
        $sortOrder = 3000;

        foreach ($this->permissions as $category => $categoryPermissions) {
            foreach ($categoryPermissions as $permission) {
                Permission::updateOrCreate(
                    [
                        'name' => $permission['name'],
                        'guard_name' => 'web',
                    ],
                    [
                        'module' => 'SystemCore',
                        'description' => $permission['description'].' ('.$category.')',
                        'sort_order' => $sortOrder++,
                    ]
                );

                $this->command->info("Created/Updated permission: {$permission['name']} (SystemCore - {$category})");
            }
        }
    }

    /**
     * Update existing roles with appropriate SystemCore permissions
     */
    protected function updateRolePermissions(): void
    {
        $this->updateAdminPermissions();
        $this->updateHrManagerPermissions();
        $this->updateInventoryManagerPermissions();
    }

    protected function updateAdminPermissions(): void
    {
        // Super Admin gets all permissions
        $superAdmin = Role::where('name', 'super_admin')->first();
        if ($superAdmin) {
            $superAdmin->syncPermissions(Permission::all());
            $this->command->info('Updated Super Admin role with all permissions');
        }

        // Admin gets all SystemCore permissions
        $admin = Role::where('name', 'admin')->first();
        if ($admin) {
            $systemCorePermissions = Permission::where('module', 'SystemCore')->pluck('name')->toArray();
            $existingPermissions = $admin->permissions()
                ->whereNotIn('module', ['SystemCore'])
                ->pluck('name')
                ->toArray();

            $admin->syncPermissions(array_merge($systemCorePermissions, $existingPermissions));
            $this->command->info('Updated Admin role with all SystemCore permissions');
        }
    }

    protected function updateHrManagerPermissions(): void
    {
        $role = Role::where('name', 'hr_manager')->first();
        if (! $role) {
            return;
        }

        $permissions = [
            'systemcore.view-products',
            'systemcore.view-categories',
        ];

        $existingPermissions = $role->permissions()
            ->whereNotIn('module', ['SystemCore'])
            ->pluck('name')
            ->toArray();

        $role->syncPermissions(array_merge($permissions, $existingPermissions));
        $this->command->info('Updated HR Manager role with view-only SystemCore permissions');
    }

    protected function updateInventoryManagerPermissions(): void
    {
        $role = Role::where('name', 'inventory_manager')->first();
        if (! $role) {
            return;
        }

        $permissions = Permission::where('module', 'SystemCore')->pluck('name')->toArray();

        $existingPermissions = $role->permissions()
            ->whereNotIn('module', ['SystemCore'])
            ->pluck('name')
            ->toArray();

        $role->syncPermissions(array_merge($permissions, $existingPermissions));
        $this->command->info('Updated Inventory Manager role with all SystemCore permissions');
    }
}
