<?php

namespace App\Console\Commands;

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

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

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

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

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

        // Migrate Classifications
        $this->info('Migrating classifications...');
        $legacyClassifications = $legacyConn->table('classifications')->get();

        $this->withProgressBar($legacyClassifications, function ($legacy) {
            DB::table('classifications')->updateOrInsert(
                ['id' => $legacy->id],
                [
                    'name' => $legacy->name,
                    'is_active' => $legacy->status == '1' ? IsActive::ACTIVE->value : IsActive::INACTIVE->value,
                    'created_at' => $legacy->created_at,
                    'updated_at' => $legacy->updated_at,
                    'deleted_at' => $legacy->deleted_at,
                ]
            );
        });
        $this->newLine();

        // Migrate Sub Classifications
        $this->info('Migrating sub classifications...');
        $legacySubClassifications = $legacyConn->table('sub_classifications')->get();

        $this->withProgressBar($legacySubClassifications, function ($legacy) {
            DB::table('sub_classifications')->updateOrInsert(
                ['id' => $legacy->id],
                [
                    'classification_id' => $legacy->classification,
                    'name' => $legacy->name,
                    'is_active' => $legacy->status == '1' ? IsActive::ACTIVE->value : IsActive::INACTIVE->value,
                    'created_at' => $legacy->created_at,
                    'updated_at' => $legacy->updated_at,
                    'deleted_at' => $legacy->deleted_at,
                ]
            );
        });
        $this->newLine();

        $this->info('Migration completed successfully!');
    }
}
