<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use App\Models\User;
use App\Http\Api\fiver;
use Illuminate\Support\Facades\DB;

class NexusUserMigrate extends Command
{
    protected $signature = 'nexus:migrate-user';
    protected $description = 'Migrate user yang belum ada di API';

    public function handle()
    {
        $api = new fiver();

        // ambil user yang belum ada di tabel migrated
        $users = User::whereNotIn('name', function ($query) {
            $query->select('username')->from('nx_migrated_users');
        })->get();

        foreach ($users as $user) {

            $result = $api->createUser($user->name);

            if(
                (isset($result['status']) && $result['status']) ||
                (isset($result['message']) && str_contains($result['message'], 'exists'))
            ){

                // simpan ke tabel tracking
                DB::table('nx_migrated_users')->insert([
                    'username' => $user->name
                ]);

                $this->info("SUCCESS : ".$user->name);

            }else{

                $this->error("FAILED : ".$user->name);

            }

            usleep(150000); // lebih cepat
        }

        $this->info("MIGRASI SELESAI");
    }
}