<?php

namespace App\Console\Commands\Migrations;

use App\Models\Initiative;
use Illuminate\Support\Facades\DB;

class InitiativeResultMigration extends BaseMigration
{
    protected string $oldTableName = 'sek_initiative_results';

    protected string $modelName = 'Initiative 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 'Initiative Result';
    }

    protected function getModelClass(): string
    {
        return 'initiative_results'; // This is a table, not a model
    }

    protected function createModel(array $data): void
    {
        // Insert into initiative_results table using raw DB query to preserve ID
        DB::table('initiative_results')->insert($data);
    }

    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} initiative 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 initiative result: {$data['id']} - Initiative {$data['initiative_id']}");
                    } catch (\Exception $e) {
                        $this->stats['errors']++;
                        $this->error("❌ Error creating initiative result ID {$oldRecord->id}: {$e->getMessage()}");
                    }
                } else {
                    $this->stats['skipped']++;
                    $this->warn("⚠️  Skipped initiative result ID {$oldRecord->id} (validation failed)");
                }
            }
        });

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

    protected function mapData($oldRecord): array
    {
        return [
            'id' => $oldRecord->id,
            'initiative_id' => $oldRecord->initiative_id,
            'expected_q1' => $oldRecord->quarter_1_expected,
            'actual_q1' => $oldRecord->quarter_1_actual,
            'expected_q2' => $oldRecord->quarter_2_expected,
            'actual_q2' => $oldRecord->quarter_2_actual,
            'expected_q3' => $oldRecord->quarter_3_expected,
            'actual_q3' => $oldRecord->quarter_3_actual,
            'expected_q4' => $oldRecord->quarter_4_expected,
            'actual_q4' => $oldRecord->quarter_4_actual,
            'created_at' => $oldRecord->created_at,
            'updated_at' => $oldRecord->modified_at ?: $oldRecord->created_at, // Use created_at if modified_at is null
            // Note: created_by is not included as it doesn't exist in the new table
        ];
    }

    protected function validateData(array $data): bool
    {
        // Check if initiative exists
        if (! Initiative::find($data['initiative_id'])) {
            $this->warn("⚠️  Initiative with ID {$data['initiative_id']} does not exist");

            return false;
        }

        // Check if result already exists
        $exists = DB::table('initiative_results')
            ->where('id', $data['id'])
            ->exists();

        if ($exists) {
            $this->warn("⚠️  Initiative result with ID {$data['id']} already exists");

            return false;
        }

        return true;
    }

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