<?php

namespace App\Console\Commands;

use App\Models\Dealer;
use App\Models\DealerProvisioningRun;
use App\Models\Department;
use App\Models\User;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use Spatie\Permission\Models\Role;

class ResetToDefaultDealer extends Command
{
    protected $signature = 'app:reset-to-default-dealer
                            {--dry-run : Show what would be deleted without making changes}';

    protected $description = 'Delete all non-default dealers and their tenant-scoped data, leaving only the default dealer.';

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

        $defaultDealers = Dealer::query()
            ->where('is_default', true)
            ->get();

        if ($defaultDealers->isEmpty()) {
            $this->error('No default dealer found (is_default = true). Aborting.');

            return 1;
        }

        if ($defaultDealers->count() > 1) {
            $this->error('More than one default dealer found. Aborting to avoid unsafe cleanup.');

            return 1;
        }

        /** @var Dealer $defaultDealer */
        $defaultDealer = $defaultDealers->first();

        $this->info(sprintf(
            'Default dealer: [ID %d] %s (%s)',
            $defaultDealer->id,
            $defaultDealer->name,
            $defaultDealer->code ?? 'NO-CODE'
        ));

        $otherDealers = Dealer::query()
            ->where('id', '!=', $defaultDealer->id)
            ->get();

        if ($otherDealers->isEmpty()) {
            $this->info('No non-default dealers found. Nothing to clean up.');

            return 0;
        }

        $dealerIds = $otherDealers->pluck('id')->all();

        $userCount = User::query()
            ->whereIn('dealer_id', $dealerIds)
            ->count();

        $departmentCount = Department::query()
            ->whereIn('dealer_id', $dealerIds)
            ->count();

        $branchCount = \App\Models\Branch::query()
            ->withoutGlobalScope('dealer_scope')
            ->whereIn('dealer_id', $dealerIds)
            ->count();

        $provisioningRunCount = DealerProvisioningRun::query()
            ->whereIn('dealer_id', $dealerIds)
            ->count();

        $roleCount = Role::query()
            ->whereIn('dealer_id', $dealerIds)
            ->count();

        $this->line('');
        $this->info('Non-default dealers to be deleted:');

        foreach ($otherDealers as $dealer) {
            $this->line(sprintf(
                '  - [ID %d] %s (%s)',
                $dealer->id,
                $dealer->name,
                $dealer->code ?? 'NO-CODE'
            ));
        }

        $this->line('');
        $this->info('Summary of related tenant-scoped data to be removed:');
        $this->line("  - Users: {$userCount}");
        $this->line("  - Departments: {$departmentCount}");
        $this->line("  - Branches: {$branchCount}");
        $this->line("  - Dealer provisioning runs: {$provisioningRunCount}");
        $this->line("  - Roles (Spatie, dealer-scoped): {$roleCount}");

        if ($dryRun) {
            $this->line('');
            $this->info('Dry run only. No data has been deleted.');

            return 0;
        }

        if (! $this->confirm('Are you sure you want to delete ALL non-default dealers and their tenant-scoped data?', false)) {
            $this->warn('Aborted by user.');

            return 0;
        }

        DB::transaction(function () use ($dealerIds): void {
            // Delete users for non-default dealers.
            User::query()
                ->whereIn('dealer_id', $dealerIds)
                ->delete();

            // Delete departments for non-default dealers.
            Department::query()
                ->whereIn('dealer_id', $dealerIds)
                ->delete();

            // Delete dealer provisioning runs.
            DealerProvisioningRun::query()
                ->whereIn('dealer_id', $dealerIds)
                ->delete();

            // Delete dealer-scoped roles (Spatie).
            Role::query()
                ->whereIn('dealer_id', $dealerIds)
                ->delete();

            // Finally, delete the dealers themselves.
            Dealer::query()
                ->whereIn('id', $dealerIds)
                ->delete();
        });

        $this->info('Cleanup complete. Only the default dealer and its data remain.');

        return 0;
    }
}

