<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;

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

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

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

        $legacyConn = DB::connection('mysql_second');
        $legacyJournalists = $legacyConn->table('journalists')->get();

        if ($legacyJournalists->isEmpty()) {
            $this->warn('No journalists found in legacy database.');

            return;
        }

        $this->withProgressBar($legacyJournalists, function ($legacy) {
            // Find corresponding partner media (outlet) in the NEW database
            // legacy 'media' column is the partner_media_id
            $partnerMedia = DB::table('partner_media')->where('id', $legacy->media)->first();

            if (! $partnerMedia) {
                // If partner media doesn't exist, we skip as it's required
                return;
            }

            DB::table('journalists')->updateOrInsert(
                ['id' => $legacy->id],
                [
                    'partner_media_id' => $partnerMedia->id,
                    'name' => Str::limit($legacy->name, 100),
                    'email' => Str::limit($legacy->email, 254),
                    'phone_number' => Str::limit($legacy->phone, 20),
                    'press_card' => Str::limit($legacy->press_card, 100),
                    'ukw_certificate' => Str::limit($legacy->certificate, 100),
                    'created_at' => $legacy->created_at ?? now(),
                    'updated_at' => $legacy->updated_at ?? now(),
                    'deleted_at' => $legacy->deleted_at,
                ]
            );
        });

        $this->newLine();
        $this->info('Journalist migration completed successfully!');
    }
}
