<?php

use App\Models\Branch;
use App\Models\Dealer;
use App\Models\User;
use App\Support\BranchCodeGenerator;
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    /**
     * Run the migrations.
     */
    public function up(): void
    {
        Schema::table('users', function (Blueprint $table): void {
            $table->foreignId('branch_id')
                ->nullable()
                ->after('department_id')
                ->constrained()
                ->nullOnDelete();
        });

        $this->backfillDefaultDealerUsers();
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        Schema::table('users', function (Blueprint $table): void {
            $table->dropConstrainedForeignId('branch_id');
        });
    }

    private function backfillDefaultDealerUsers(): void
    {
        $defaultDealer = Dealer::query()
            ->where('is_default', true)
            ->first();

        if (! $defaultDealer) {
            return;
        }

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

        if (! $hasAnyBranch) {
            $branch = new Branch();
            $branch->dealer_id = $defaultDealer->id;
            $branch->name = 'Main';
            $branch->code = BranchCodeGenerator::nextForDealer($defaultDealer);
            $branch->is_default = true;
            $branch->is_active = true;
            $branch->save();
        } else {
            $branch = Branch::withoutGlobalScope('dealer_scope')
                ->where('dealer_id', $defaultDealer->id)
                ->where('is_default', true)
                ->first()
                ?? Branch::withoutGlobalScope('dealer_scope')
                    ->where('dealer_id', $defaultDealer->id)
                    ->orderBy('id')
                    ->first();
        }

        if (! $branch) {
            return;
        }

        User::query()
            ->where('dealer_id', $defaultDealer->id)
            ->whereNull('branch_id')
            ->update(['branch_id' => $branch->id]);
    }
};

