<?php

namespace App\Console\Commands\Migrations;

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

class PerformanceWalletMigration extends BaseMigration
{
    protected string $oldTableName = 'sek_performance_wallets';

    protected string $modelName = 'Performance Wallets';

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

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

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

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

    protected function mapData($oldRecord): array
    {
        return [
            'id' => $oldRecord->id,
            'name' => $oldRecord->wallet_name,
            'start_date' => $this->parseDateTime($oldRecord->wallet_start_date),
            'expected_end_date' => $this->parseDateTime($oldRecord->wallet_expected_end_date),
            'description' => $oldRecord->wallet_description,
            'performance_card_id' => $oldRecord->performance_card_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 performance wallet with this ID already exists
        if (PerformanceWallet::find($data['id'])) {
            $this->warn("⚠️  Performance wallet 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 name is not empty
        if (empty(trim($data['name']))) {
            $this->warn("⚠️  Performance wallet ID {$data['id']} has empty name");

            return false;
        }

        return true;
    }

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