<?php

namespace App\Console\Commands\Migrations;

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

class PerformanceCardProductMigration extends BaseMigration
{
    protected string $oldTableName = 'sek_performance_card_products';

    protected string $modelName = 'Performance Card Products';

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

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

    protected function createModel(array $data): void
    {
        // Insert into pivot table using raw DB query
        DB::table('performance_card_sekaya_value')->insert([
            'performance_card_id' => $data['performance_card_id'],
            'sekaya_value_id' => $data['sekaya_value_id'],
        ]);
    }

    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 products 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 product relationship: PC {$data['performance_card_id']} -> SV {$data['sekaya_value_id']}");
                    } catch (\Exception $e) {
                        $this->stats['errors']++;
                        $this->error("❌ Error creating performance card product relationship PC {$oldRecord->performance_card_id} -> SV {$oldRecord->value_id}: {$e->getMessage()}");
                    }
                } else {
                    $this->stats['skipped']++;
                    $this->warn("⚠️  Skipped performance card product relationship PC {$oldRecord->performance_card_id} -> SV {$oldRecord->value_id} (validation failed)");
                }
            }
        });

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

    protected function mapData($oldRecord): array
    {
        return [
            'performance_card_id' => $oldRecord->performance_card_id,
            'sekaya_value_id' => $oldRecord->value_id,
        ];
    }

    protected function validateData(array $data): bool
    {
        // 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 sekaya value exists
        if (! SekayaValue::find($data['sekaya_value_id'])) {
            $this->warn("⚠️  SekayaValue with ID {$data['sekaya_value_id']} does not exist");

            return false;
        }

        // Check if relationship already exists
        $exists = DB::table('performance_card_sekaya_value')
            ->where('performance_card_id', $data['performance_card_id'])
            ->where('sekaya_value_id', $data['sekaya_value_id'])
            ->exists();

        if ($exists) {
            $this->warn("⚠️  Relationship between Performance Card {$data['performance_card_id']} and SekayaValue {$data['sekaya_value_id']} already exists");

            return false;
        }

        return true;
    }

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