<?php

namespace DefStudio\GameEngine\Commands;

use Illuminate\Console\Command;
use Illuminate\Support\Collection;
use Spatie\Permission\Models\Role;
use Spatie\Permission\Models\Permission;
use Illuminate\Console\View\Components\TwoColumnDetail;

class SyncRolesCommand extends Command
{
    public $signature = 'game-engine:sync-roles';

    public $description = 'Sync Game Engine roles to the database';

    public function handle(): int
    {
        $this->info('Syncing User Roles');
        Permission::each(fn(Permission $permission) => $permission->delete());

        foreach (config('game-engine.users.roles') as $roleName => $roleConfig) {
            $this->twoColumnDetail()->render(
                $roleName,
                '<fg=yellow;options=bold>RUNNING</>'
            );

            /** @var Role $role */
            $role = Role::findOrCreate($roleName);

            if ($role->wasRecentlyCreated) {
                $this->twoColumnDetail()->render(
                    $roleName,
                    '<fg=blue;options=bold>CREATED</>'
                );
            }

            $permissions = Collection::empty();
            foreach (data_get($roleConfig, 'permissions', []) as $key => $permissionData) {
                if (!is_array($permissionData)) {
                    $permissions->push($permissionData);

                    continue;
                }

                foreach ($permissionData as $subPermission) {
                    $permissions->push($key.'.'.$subPermission);
                }
            }

            $role->givePermissionTo(
                $permissions
                    ->map(function(string $permissionName): Permission {
                        /** @var Permission $permission */
                        $permission = Permission::findOrCreate($permissionName);

                        if ($permission->wasRecentlyCreated) {
                            $this->twoColumnDetail()->render(
                                $permissionName,
                                '<fg=blue;options=bold>CREATED</>'
                            );
                        }

                        $this->twoColumnDetail()->render(
                            $permissionName,
                            '<fg=blue;options=bold>GRANTED</>'
                        );

                        return $permission;
                    })
            );

            $this->twoColumnDetail()->render(
                $roleName,
                '<fg=green;options=bold>DONE</>'
            );
        }

        return self::SUCCESS;
    }

    public function twoColumnDetail(): TwoColumnDetail
    {
        return new TwoColumnDetail($this->getOutput());
    }
}
