<?php

namespace App\Console\Commands\Migrations;

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

class InitiativeProductMigration extends BaseMigration
{
    protected string $oldTableName = 'sek_initiative_products';

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

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

    protected function createModel(array $data): void
    {
        // Insert into pivot table using raw DB query
        DB::table('initiative_products')->insert([
            'initiative_id' => $data['initiative_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} initiative product relationships 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 product relationship: Initiative {$data['initiative_id']} -> SV {$data['sekaya_value_id']}");
                    } catch (\Exception $e) {
                        $this->stats['errors']++;
                        $this->error("❌ Error creating initiative product relationship Initiative {$oldRecord->initiative_id} -> SV {$oldRecord->value_id}: {$e->getMessage()}");
                    }
                } else {
                    $this->stats['skipped']++;
                    $this->warn("⚠️  Skipped initiative product relationship Initiative {$oldRecord->initiative_id} -> SV {$oldRecord->value_id} (validation failed)");
                }
            }
        });

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

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

    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 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('initiative_products')
            ->where('initiative_id', $data['initiative_id'])
            ->where('sekaya_value_id', $data['sekaya_value_id'])
            ->exists();

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

            return false;
        }

        return true;
    }

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