<?php

namespace App\Console\Commands;

use App\Enums\IssueSentiment;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;

class MigrateIssueManagementCommand extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'migrate:issue-management';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Migrate issue management data from legacy database';

    /**
     * Execute the console command.
     */
    public function handle()
    {
        $this->info('Starting issue management migration...');

        $legacyConn = DB::connection('mysql_second');

        // Get legacy issue management
        $legacyIssues = $legacyConn->table('issue_management')->get();

        if ($legacyIssues->isEmpty()) {
            $this->warn('No issue management records found in legacy database.');

            return;
        }

        $this->withProgressBar($legacyIssues, function ($legacy) {
            DB::table('issue_management')->updateOrInsert(
                ['id' => $legacy->id],
                [
                    'media_monitoring_id' => $legacy->media_monitoring,
                    'location_id' => $legacy->locus,
                    'sub_location_id' => $legacy->sub_locus,
                    'classification_id' => $legacy->classification,
                    'sub_classification_id' => $legacy->sub_classification,
                    'issue' => $this->mapSentiment($legacy->issue),
                    'response' => $this->mapSentiment($legacy->response),
                    'description' => $legacy->description ?? '-',
                    'created_at' => $legacy->created_at ?? now(),
                    'updated_at' => $legacy->updated_at ?? now(),
                    'deleted_at' => $legacy->deleted_at,
                ]
            );
        });
        $this->newLine();

        $this->info('Issue management migration completed successfully!');
    }

    private function mapSentiment(string $legacyValue): int
    {
        return match (strtolower($legacyValue)) {
            'positif' => IssueSentiment::POSITIVE->value,
            'negatif' => IssueSentiment::NEGATIVE->value,
            'netral' => IssueSentiment::NEUTRAL->value,
            'krisis' => IssueSentiment::CRISIS->value,
            default => IssueSentiment::NEUTRAL->value,
        };
    }
}
