<?php

declare(strict_types=1);

namespace App\Console\Commands;

use App\Jobs\SyncBackendDataPool;
use App\Jobs\TransformDataPoolToProduction;
use Illuminate\Console\Command;

use function Laravel\Prompts\confirm;
use function Laravel\Prompts\info;
use function Laravel\Prompts\spin;
use function Laravel\Prompts\warning;

class RebuildFromDataPoolCommand extends Command
{
    /**
     * The name and signature of the console command.
     */
    protected $signature = 'backend:rebuild
                            {--batch-size=1000 : Number of records to process per batch}
                            {--transform-batch-size=100 : Number of records to process per batch for transformation}
                            {--queue : Dispatch jobs to the queue instead of running synchronously}';

    /**
     * The console command description.
     */
    protected $description = 'Complete rebuild: Full sync from backend + transformation to production tables';

    /**
     * Execute the console command.
     */
    public function handle(): int
    {
        info('Preparing for COMPLETE REBUILD');
        warning('This will:');
        warning('1. Truncate and rebuild backend_data_pool (full sync)');
        warning('2. Transform all data into companies and transactions');

        if (! $this->option('no-interaction') && ! confirm('Do you want to continue?', true)) {
            info('Rebuild cancelled.');

            return self::SUCCESS;
        }

        $batchSize = (int) $this->option('batch-size');
        $transformBatchSize = (int) $this->option('transform-batch-size');
        $useQueue = $this->option('queue');

        // Step 1: Full Sync
        info('Step 1/2: Full Sync from Backend');
        $syncJob = new SyncBackendDataPool(
            fullSync: true,
            batchSize: $batchSize
        );

        if ($useQueue) {
            info('Dispatching sync job to queue...');
            dispatch($syncJob);
            info('Sync job dispatched!');
            warning('Please wait for the sync job to complete before transformation.');

            return self::SUCCESS;
        } else {
            spin(
                fn () => $syncJob->handle(),
                'Syncing data from backend...'
            );
            info('✓ Sync completed!');
        }

        $this->newLine();

        // Step 2: Transform Data
        info('Step 2/2: Transform Data Pool to Production');
        $transformJob = new TransformDataPoolToProduction(batchSize: $transformBatchSize);

        spin(
            fn () => $transformJob->handle(),
            'Transforming data...'
        );
        info('✓ Transformation completed!');

        $this->newLine();
        info('Complete rebuild finished successfully!');

        return self::SUCCESS;
    }
}
