<?php

namespace App\Console\Commands\Migrations;

use App\Models\PerformanceCard;
use App\Models\PerformanceCardResult;
use Illuminate\Support\Facades\DB;

class PerformanceCardResultMigration extends BaseMigration
{
    protected string $oldTableName = 'sek_performance_card_results';

    protected string $modelName = 'Performance Card Results';

    public function migrate(bool $dryRun = false, int $batchSize = 1000, int $startFrom = 0): void
    {
        $oldDb = DB::connection($this->connection);
        $this->processData($oldDb, $dryRun, $startFrom, $batchSize);
    }

    protected function getModelName(): string
    {
        return 'Performance Card Result';
    }

    protected function getModelClass(): string
    {
        return 'App\\Models\\PerformanceCardResult';
    }

    protected function createModel(array $data): void
    {
        // Use raw DB insertion to preserve the original ID
        DB::table('performance_card_results')->insert([
            'id' => $data['id'],
            'performance_card_id' => $data['performance_card_id'],
            'result' => $data['result'],
            'created_by' => $data['created_by'],
            'created_at' => $data['created_at'],
            'updated_at' => $data['updated_at'],
        ]);
    }

    protected function processData($oldDb, bool $dryRun, int $startFrom, int $batchSize): void
    {
        $query = $oldDb->table($this->oldTableName)
            ->orderBy('id')
            ->offset($startFrom);

        $totalRecords = $oldDb->table($this->oldTableName)->count();
        $this->info("📊 Found {$totalRecords} performance card results to migrate");

        if ($totalRecords === 0) {
            $this->info('✅ No records to migrate');

            return;
        }

        $bar = $this->command->getOutput()->createProgressBar($totalRecords);
        $bar->start();

        $query->chunk($batchSize, function ($oldRecords) use ($dryRun, $bar) {
            foreach ($oldRecords as $oldRecord) {
                $bar->advance();

                $data = $this->mapData($oldRecord);

                if ($this->validateData($data)) {
                    try {
                        if (! $dryRun) {
                            $this->createModel($data);
                        }
                        $this->stats['migrated']++;
                        $this->info("✅ Created performance card result: {$data['result']} (ID: {$data['id']})");
                    } catch (\Exception $e) {
                        $this->stats['errors']++;
                        $this->error("❌ Error creating performance card result ID {$oldRecord->id}: {$e->getMessage()}");
                    }
                } else {
                    $this->stats['skipped']++;
                    $this->warn("⚠️  Skipped performance card result ID {$oldRecord->id} (validation failed)");
                }
            }
        });

        $bar->finish();
        $this->info('');  // Add newline
    }

    protected function mapData($oldRecord): array
    {
        return [
            'id' => $oldRecord->id,
            'performance_card_id' => $oldRecord->performance_card_id,
            'result' => $oldRecord->result,
            'created_by' => $oldRecord->created_by,
            'created_at' => $this->parseDateTime($oldRecord->created_at),
            'updated_at' => $this->parseDateTime($oldRecord->modified_at ?? $oldRecord->created_at),
        ];
    }

    protected function validateData(array $data): bool
    {
        // Check if performance card result with this ID already exists
        if (PerformanceCardResult::find($data['id'])) {
            $this->warn("⚠️  Performance card result with ID {$data['id']} already exists");

            return false;
        }

        // Check if performance card exists
        if (! PerformanceCard::find($data['performance_card_id'])) {
            $this->warn("⚠️  Performance card with ID {$data['performance_card_id']} does not exist");

            return false;
        }

        // Check if result is not empty
        if (empty(trim($data['result']))) {
            $this->warn("⚠️  Performance card result ID {$data['id']} has empty result");

            return false;
        }

        return true;
    }

    protected function getStatsSummary(): array
    {
        return [
            'Performance-card-results' => [
                'Total' => $this->stats['total'] ?? 0,
                'Migrated' => $this->stats['migrated'] ?? 0,
                'Skipped' => $this->stats['skipped'] ?? 0,
                'Errors' => $this->stats['errors'] ?? 0,
            ],
        ];
    }
}
