<?php

namespace App\Console\Commands;

use App\Models\Branch;
use App\Models\Dealer;
use App\Models\User;
use App\Support\BranchCodeGenerator;
use Illuminate\Console\Command;

class EnsureDefaultBranches extends Command
{
    protected $signature = 'dealers:ensure-default-branches
                            {--with-user-backfill : Assign users with NULL branch_id to the created default branch}';

    protected $description = 'Ensure every dealer has at least one default branch (idempotent recovery utility).';

    public function handle(): int
    {
        $withUserBackfill = (bool) $this->option('with-user-backfill');

        $dealers = Dealer::query()->get();
        if ($dealers->isEmpty()) {
            $this->info('No dealers found.');

            return 0;
        }

        foreach ($dealers as $dealer) {
            $this->line("Checking dealer [{$dealer->id}] {$dealer->code} - {$dealer->name}");

            $hasAnyBranch = Branch::withoutGlobalScope('dealer_scope')
                ->where('dealer_id', $dealer->id)
                ->exists();

            if ($hasAnyBranch) {
                $this->line('  - Branches already exist. Skipping creation.');
                continue;
            }

            $address = sprintf(
                '[RECOVERY] Address pending for dealer %s (%s)',
                $dealer->name ?? 'Unknown',
                $dealer->code ?? 'NO-CODE'
            );

            $branch = new Branch();
            $branch->dealer_id = $dealer->id;
            $branch->name = 'Main';
            $branch->address = $address;
            $branch->code = BranchCodeGenerator::nextForDealer($dealer);
            $branch->is_default = true;
            $branch->is_active = true;
            $branch->save();

            $this->info("  - Created default branch [{$branch->id}] {$branch->code} for dealer.");

            if ($withUserBackfill) {
                $updated = User::query()
                    ->where('dealer_id', $dealer->id)
                    ->whereNull('branch_id')
                    ->update(['branch_id' => $branch->id]);

                $this->line("  - User backfill: {$updated} user(s) assigned to branch {$branch->id}.");
            }
        }

        $this->info('Done. All dealers now have at least one branch or already had branches.');

        return 0;
    }
}

