<?php

namespace App\Console\Commands\Migrations;

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

class CenterMigration extends BaseMigration
{
    protected string $modelClass = Center::class;

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

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

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

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

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

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

            return;
        }

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

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

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

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

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

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

    /**
     * Map old database data to new model structure
     */
    protected function mapData(object $oldCenter): array
    {
        $data = [
            'id' => $oldCenter->id, // Preserve original ID
            'name' => $oldCenter->name_ar ?? "Center {$oldCenter->id}",
            'city_id' => $oldCenter->city_id,
            'families_count' => $oldCenter->number_of_families ?? 0,
            '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',
            'city_id' => 'required|integer|exists:cities,id',
            'families_count' => 'nullable|integer|min:0',
        ]);

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

            return false;
        }

        return true;
    }
}
