<?php

namespace App\Console\Commands;

use Illuminate\Console\Attributes\Description;
use Illuminate\Console\Attributes\Signature;
use Illuminate\Console\Command;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\DB;

#[Signature('migrate:users:configure')]
#[Description('Configure users migrations settings like roles.')]
class MigrateUsersConfigure extends Command
{

    private function getWpRoles(): array
    {
        $wpRoles = ['administrator', 'editor', 'author', 'contributor', 'subscriber'];
        $customWpRoles = ['bot'];

        return array_merge($wpRoles, $customWpRoles);
    }

    private function getOldXfGroups(): array|Collection
    {
        return DB::connection('old_xf')->table('user_group')->pluck('title', 'user_group_id');
    }

    public function handle()
    {
        $wpRoles = $this->getWpRoles();
        $roleMap = [];
        foreach ($wpRoles as $role) {
            $roleMap[$role] = (int) $this->ask("XenForo group ID linked to role {$role}");
        }
        DB::table('migration_settings')
            ->updateOrInsert([
                'key' => 'wp_role_to_xf_group'
            ], [
               'value' => json_encode($roleMap), 'updated_at' => now()
            ]);

        $oldXfGroups = $this->getOldXfGroups();
        $groupMap = [];
        foreach ($oldXfGroups as $id => $title) {
            $groupMap[$id] = (int) $this->ask("Xenforo group ID linked to old XF group {$title}|{$id}");
        }
        DB::table('migration_settings')
            ->updateOrInsert([
                'key' => 'old_xf_group_to_xf_group'
            ],[
                'value' => json_encode($groupMap), 'updated_at' => now()
            ]);

        $this->info('XF groups updated.');
    }
}
