<?php

namespace App\Console\Commands;

use App\Models\User;
use App\Services\UserBranchAssignmentService;
use Illuminate\Console\Command;

class RepairUserBranchAssignments extends Command
{
    protected $signature = 'branches:repair-user-assignments {--dry-run : Report inconsistencies without changing data}';

    protected $description = 'Synchronize users.primary_branch_id with branch_user primary assignments';

    public function handle(UserBranchAssignmentService $assignments): int
    {
        $dryRun = (bool) $this->option('dry-run');
        $scanned = 0;
        $changed = 0;

        User::query()->orderBy('id')->chunkById(200, function ($users) use ($assignments, $dryRun, &$scanned, &$changed): void {
            foreach ($users as $user) {
                $scanned++;
                $result = $assignments->repair($user, $dryRun);

                if (! $result['changed']) {
                    continue;
                }

                $changed++;
                $before = $result['primary_before'] ?? 'none';
                $after = $result['primary_after'] ?? 'none';
                $branches = $result['branch_ids'] === [] ? 'none' : implode(',', $result['branch_ids']);

                $this->line(sprintf(
                    'User #%d (%s): primary %s -> %s; branches [%s]%s',
                    $user->id,
                    $user->username ?: $user->email ?: $user->name,
                    $before,
                    $after,
                    $branches,
                    $dryRun ? ' [dry-run]' : ''
                ));
            }
        });

        $this->info(sprintf(
            '%s %d user(s); %d assignment set(s) %s.',
            $dryRun ? 'Scanned' : 'Processed',
            $scanned,
            $changed,
            $dryRun ? 'need repair' : 'repaired'
        ));

        return self::SUCCESS;
    }
}
