<?php

namespace App\Console\Commands\Migrations;

use App\Models\State;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;

class StateMigration extends BaseMigration
{
    protected string $modelClass = State::class;

    /**
     * Get the model class
     */
    protected function getModelClass(): string
    {
        return State::class;
    }

    /**
     * Migrate states from old database
     */
    public function migrate(bool $dryRun = false, int $batchSize = 100, int $startFrom = 0): void
    {
        $this->command->info('👥 Starting states migration...');

        $oldDb = DB::connection($this->connection);

        // Get total count
        $totalCount = $oldDb->table('sek_states')->count();
        $this->stats['total'] = $totalCount;

        $this->info("📊 Found {$totalCount} states to migrate");

        if ($totalCount === 0) {
            $this->warn('⚠️  No states found to migrate');

            return;
        }

        // Process in batches
        $processed = 0;
        $bar = $this->command->getOutput()->createProgressBar($totalCount);

        $oldDb->table('sek_states')
            ->orderBy('id')
            ->skip($startFrom)
            ->chunk($batchSize, function ($oldStates) use ($dryRun, &$processed, $bar) {
                foreach ($oldStates as $oldState) {
                    try {
                        $mappedData = $this->mapData($oldState);

                        if ($this->validateData($mappedData)) {
                            if (! $dryRun) {
                                // Check if state with this ID already exists
                                if ($this->recordExists($mappedData['id'])) {
                                    $this->warn("⚠️  State with ID {$mappedData['id']} already exists, skipping");
                                    $this->stats['skipped']++;
                                } else {
                                    // Create state
                                    $this->createModel($mappedData);
                                    $this->stats['migrated']++;
                                }
                            } else {
                                $this->stats['migrated']++;
                            }
                        } else {
                            $this->stats['skipped']++;
                            $this->warn("⚠️  Skipped state ID {$oldState->id}: validation failed");
                        }
                    } catch (\Exception $e) {
                        $this->stats['errors']++;
                        $this->error("❌ Error migrating state ID {$oldState->id}: ".$e->getMessage());
                    }

                    $processed++;
                    $bar->advance();
                }
            });

        $bar->finish();
        $this->command->newLine();
        $this->info('✅ States migration completed');
    }

    /**
     * Get the model name for display purposes
     */
    protected function getModelName(): string
    {
        return 'State';
    }

    /**
     * Map old database data to new model structure
     */
    protected function mapData(object $oldState): array
    {
        $data = [
            'id' => $oldState->id, // Preserve original ID
            'name' => $oldState->name_ar ?? "State {$oldState->id}",
            'created_at' => now(),
            'updated_at' => now(),
        ];

        return $data;
    }

    /**
     * Validate the mapped data
     */
    protected function validateData(array $data): bool
    {
        $validator = Validator::make($data, [
            'id' => 'required|integer|min:1',
            'name' => 'required|string|max:255',
        ]);

        if ($validator->fails()) {
            $this->error('Validation errors: '.implode(', ', $validator->errors()->all()));

            return false;
        }

        return true;
    }
}
