<?php

namespace App\Console\Commands\Migrations;

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

class InitiativeOperationGoalMigration extends BaseMigration
{
    protected string $oldTableName = 'sek_initiative_goals';

    protected string $modelName = 'Initiative Operation Goals';

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

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

    protected function createModel(array $data): void
    {
        // Insert into initiative_operation_goals table using raw DB query to preserve ID
        DB::table('initiative_operation_goals')->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 operation goals 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 operation goal: {$data['id']} - {$data['performance_criteria']}");
                    } catch (\Exception $e) {
                        $this->stats['errors']++;
                        $this->error("❌ Error creating initiative operation goal ID {$oldRecord->id}: {$e->getMessage()}");
                    }
                } else {
                    $this->stats['skipped']++;
                    $this->warn("⚠️  Skipped initiative operation goal ID {$oldRecord->id} (validation failed)");
                }
            }
        });

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

    protected function mapData($oldRecord): array
    {
        return [
            'id' => $oldRecord->id,
            'name' => $oldRecord->goal_name ?: '', // Use empty string if null
            'performance_criteria' => $oldRecord->performance_criteria,
            'target' => $oldRecord->target_type ?: '', // Use empty string if null
            'actual' => $oldRecord->achieved_type, // This can be null
            'initiative_id' => $oldRecord->initiative_id,
            '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 goal already exists
        $exists = DB::table('initiative_operation_goals')
            ->where('id', $data['id'])
            ->exists();

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

            return false;
        }

        return true;
    }

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