<?php

namespace App\Console\Commands;

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

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

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

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

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

        // Migrate Locations (Locuses)
        $this->info('Migrating locations...');
        $legacyLocations = $legacyConn->table('locuses')->get();

        $this->withProgressBar($legacyLocations, function ($legacy) {
            DB::table('locations')->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 Locations (Sub Locuses)
        $this->info('Migrating sub locations...');
        $legacySubLocations = $legacyConn->table('sub_locuses')->get();

        $this->withProgressBar($legacySubLocations, function ($legacy) {
            DB::table('sub_locations')->updateOrInsert(
                ['id' => $legacy->id],
                [
                    'location_id' => $legacy->locus,
                    '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!');
    }
}
