<?php

namespace App\Console\Commands;

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

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

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Migrate announcement data from legacy news table where category = 1';

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

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

        // Get legacy news with category 1 (Announcements)
        $legacyAnnouncements = $legacyConn->table('news')
            ->where('category', '1')
            ->get();

        if ($legacyAnnouncements->isEmpty()) {
            $this->warn('No announcements found with category 1.');

            return;
        }

        $this->withProgressBar($legacyAnnouncements, function ($legacy) {
            DB::table('announcements')->updateOrInsert(
                ['id' => $legacy->id],
                [
                    'title' => $legacy->title,
                    'content' => $legacy->content,
                    'type' => AnnouncementType::PUBLIC->value,
                    'created_at' => $legacy->created_at ?? now(),
                    'updated_at' => $legacy->updated_at ?? now(),
                    'deleted_at' => $legacy->deleted_at,
                ]
            );
        });
        $this->newLine();

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