<?php

namespace App\Console\Commands\Migrations;

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

class CityMigration extends BaseMigration
{
    protected string $modelClass = City::class;

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

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

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

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

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

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

            return;
        }

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

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

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

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

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

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

    /**
     * Map old database data to new model structure
     */
    protected function mapData(object $oldCity): array
    {
        $data = [
            'id' => $oldCity->id, // Preserve original ID
            'name' => $oldCity->name_ar ?? "City {$oldCity->id}",
            'state_id' => $oldCity->state_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',
            'state_id' => 'required|integer|exists:states,id',
        ]);

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

            return false;
        }

        return true;
    }
}
