<?php

namespace App\Console\Commands;

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

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

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Migrate department data from legacy agencies table';

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

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

        // Migrate Departments (Agencies)
        $this->info('Migrating departments...');
        $legacyAgencies = $legacyConn->table('agencies')->get();

        $this->withProgressBar($legacyAgencies, function ($legacy) {
            DB::table('departments')->updateOrInsert(
                ['id' => $legacy->id],
                [
                    'name' => $legacy->name,
                    'alias' => Str::limit($legacy->name, 20, ''),
                    'is_active' => IsActive::ACTIVE->value,
                    'created_at' => $legacy->created_at ?? now(),
                    'updated_at' => $legacy->updated_at ?? now(),
                    'deleted_at' => $legacy->deleted_at,
                ]
            );
        });
        $this->newLine();

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