<?php

namespace App\Console\Commands\Migrations;

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

class InitiativeMigration extends BaseMigration
{
    protected string $oldTableName = 'sek_initiatives';

    protected string $modelName = 'Initiatives';

    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';
    }

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

    protected function createModel(array $data): void
    {
        // Use raw DB insertion to preserve the original ID
        DB::table('initiatives')->insert([
            'id' => $data['id'],
            'name' => $data['name'],
            'start_date' => $data['start_date'],
            'expected_end_date' => $data['expected_end_date'],
            'description' => $data['description'],
            'expected_cost' => $data['expected_cost'],
            'emergency_reserve' => $data['emergency_reserve'],
            'performance_wallet_id' => $data['performance_wallet_id'],
            '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} initiatives 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: {$data['name']} (ID: {$data['id']})");
                    } catch (\Exception $e) {
                        $this->stats['errors']++;
                        $this->error("❌ Error creating initiative ID {$oldRecord->id}: {$e->getMessage()}");
                    }
                } else {
                    $this->stats['skipped']++;
                    $this->warn("⚠️  Skipped initiative ID {$oldRecord->id} (validation failed)");
                }
            }
        });

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

    protected function mapData($oldRecord): array
    {
        return [
            'id' => $oldRecord->id,
            'name' => $oldRecord->initiative_name,
            'start_date' => $this->parseDateTime($oldRecord->initiative_start_date),
            'expected_end_date' => $this->parseDateTime($oldRecord->initiative_expected_end_date),
            'description' => $oldRecord->initiative_description,
            'expected_cost' => $oldRecord->estimated_indicator_index_value_1 ?? 0,
            'emergency_reserve' => $oldRecord->estimated_indicator_index_value_2 ?? 0,
            'performance_wallet_id' => $oldRecord->wallet_id,
            'created_by' => $oldRecord->created_by ?? 21, // Default to user ID 21 if null
            '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 initiative with this ID already exists
        if (Initiative::find($data['id'])) {
            $this->warn("⚠️  Initiative with ID {$data['id']} already exists");

            return false;
        }

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

            return false;
        }

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

            return false;
        }

        return true;
    }

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