<?php

namespace App\Console\Commands;

use App\Enums\NewsStatus;
use App\Models\News;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;

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

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

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

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

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

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

            return;
        }

        // Get a default author ID (prefer Developer or Admin)
        $defaultAuthorId = DB::table('users')->first()?->id ?? 1;

        $this->withProgressBar($legacyNews, function ($legacy) use ($defaultAuthorId) {
            // Use updateOrInsert for the basic record
            DB::table('news')->updateOrInsert(
                ['id' => $legacy->id],
                [
                    'author_id' => $defaultAuthorId,
                    'title' => $legacy->title,
                    'slug' => Str::slug($legacy->title).'-'.$legacy->id,
                    'content' => $legacy->content,
                    'excerpt' => Str::limit(strip_tags($legacy->content), 160),
                    'link' => $legacy->link ? Str::limit($legacy->link, 50, '') : null,
                    'views' => 0,
                    'status' => NewsStatus::PUBLISHED->value,
                    'published_at' => $legacy->created_at,
                    'created_at' => $legacy->created_at ?? now(),
                    'updated_at' => $legacy->updated_at ?? now(),
                    'deleted_at' => $legacy->deleted_at,
                ]
            );

            // Handle Tags using the Model (if tag exists in legacy)
            if (! empty($legacy->tag)) {
                $news = News::find($legacy->id);
                if ($news) {
                    // split by comma or other delimiter if multiple tags,
                    // legacy 'tag' column is varchar(20), likely a single tag or comma separated
                    $tags = array_map('trim', explode(',', $legacy->tag));
                    $news->syncTags($tags);
                }
            }
        });
        $this->newLine();

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