<?php

namespace App\Console\Commands;

use App\Enums\IsActive;
use App\Enums\RoleEnum;
use App\Models\User;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;

class MigrateUserCommand extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'migrate:user';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Migrate users from legacy database';

    /**
     * Execute the console command.
     */
    public function handle()
    {
        $this->info('Starting user migration...');

        $legacyUsers = DB::connection('mysql_second')->table('users')->get();

        if ($legacyUsers->isEmpty()) {
            $this->warn('No users found in legacy database.');

            return;
        }

        foreach ($legacyUsers as $legacy) {
            $user = User::where('email', $legacy->email)->first();
            $roleName = $this->mapRole($legacy->role);

            if (! $user) {

                $username = $this->generateUniqueUsername($legacy->name, $legacy->email);

                $userId = DB::table('users')->insertGetId([
                    'id' => $legacy->id,
                    'name' => Str::limit($legacy->name, 100),
                    'email' => $legacy->email,
                    'username' => $username,
                    'password' => $legacy->password,
                    'is_active' => $legacy->status == '1'
                        ? IsActive::ACTIVE->value
                        : IsActive::INACTIVE->value,
                    'email_verified_at' => now(),
                    'created_at' => $legacy->created_at ?? now(),
                    'updated_at' => $legacy->updated_at ?? now(),
                ]);

                $user = User::find($userId);

                if ($roleName) {
                    $user->syncRoles([$roleName]);
                }
            }
        }

        $this->newLine();
        $this->info('User migration completed successfully!');
    }

    private function generateUniqueUsername($name, $email)
    {
        // Try name first
        $base = Str::limit(Str::slug($name, ''), 10, '');
        if (empty($base)) {
            $base = Str::limit(explode('@', $email)[0], 10, '');
        }

        $username = $base;
        $counter = 1;

        // Ensure unique within 10 chars
        while (User::where('username', $username)->exists()) {
            $suffix = (string) $counter;
            $maxBaseLength = 10 - strlen($suffix);
            $username = substr($base, 0, $maxBaseLength).$suffix;
            $counter++;

            if ($counter > 999) {
                break;
            } // Safety
        }

        return $username;
    }

    private function mapRole($legacyRole): ?string
    {
        return match ((int) $legacyRole) {
            1 => RoleEnum::ADMINISTRATOR->value,
            2 => RoleEnum::ADMIN_MONITORING->value,
            3 => RoleEnum::PERUSAHAAN->value,
            4 => RoleEnum::ADMIN_KONTEN->value,
            5 => RoleEnum::ADMIN_KEUANGAN->value,
            default => null,
        };
    }
}
