<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use cPad\Plugins\News\Models\NewsArticle;

class ImportLegacyNewsCommand extends Command
{
    protected $signature = 'news:import-legacy {--dry-run} {--limit=500} {--start=0}';

    protected $description = 'Import News articles from legacy DB into the current Skinbase news_articles table.';

    public function handle()
    {
        $dryRun = $this->option('dry-run');
        $limit = (int) $this->option('limit');
        $start = (int) $this->option('start');

        // Verify legacy DB connection exists and is reachable
        try {
            DB::connection('legacy')->getPdo();
        } catch (\Throwable $e) {
            $this->error('Cannot connect to legacy database via connection "legacy": ' . $e->getMessage());
            Log::error('Legacy import failed - cannot connect to legacy', ['exception' => $e]);
            return 2;
        }

        if (! DB::connection('legacy')->getSchemaBuilder()->hasTable('news')) {
            $this->error('Legacy table `news` not found on legacy connection.');
            return 2;
        }

        $this->info(sprintf('Fetching up to %d legacy rows starting at %d...', $limit, $start));

        try {
            $rows = DB::connection('legacy')->table('news')
                ->orderBy('news_id')
                ->skip($start)
                ->take($limit)
                ->get();
        } catch (\Throwable $e) {
            $this->error('Failed to query legacy DB: ' . $e->getMessage());
            Log::error('Legacy import failed', ['exception' => $e]);
            return 2;
        }

        if ($rows->isEmpty()) {
            $this->info('No rows found in legacy news table.');
            return 0;
        }

        $this->info('Processing ' . $rows->count() . ' rows...');

        $created = 0;
        foreach ($rows as $row) {
            // Map fields conservatively — adjust mapping as needed for your legacy schema
            $title = $row->headline ?? ($row->title ?? '');
            $content = $row->content ?? ($row->message ?? '');
            $excerpt = $row->preview ?? null;
            $publishedAt = $row->create_date ?? ($row->published_at ?? null);

            // Best-effort author mapping: try username/uname then fallback to user id 1
            $authorId = 1;
            if (!empty($row->uname)) {
                $uid = DB::table('users')->where('username', $row->uname)->orWhere('uname', $row->uname)->value('id');
                if ($uid) {
                    $authorId = $uid;
                }
            }

            $payload = [
                'title' => $title,
                'slug' => NewsArticle::generateUniqueSlug($title),
                'excerpt' => $excerpt,
                'content' => $content,
                'cover_image' => $row->picture ?? null,
                'type' => 'announcement',
                'author_id' => $authorId,
                'category_id' => null,
                'editorial_status' => isset($row->type) && (int)$row->type === 0 ? NewsArticle::EDITORIAL_STATUS_DRAFT : NewsArticle::EDITORIAL_STATUS_PUBLISHED,
                'published_at' => $publishedAt ? date('Y-m-d H:i:s', strtotime($publishedAt)) : null,
                'is_featured' => ($row->frontpage ?? 0) == 1,
                'is_pinned' => ($row->type ?? 0) == 2,
                'views' => $row->views ?? 0,
                'canonical_url' => '/legacy/news/' . ($row->news_id ?? ''),
                'legacy_news_id' => isset($row->news_id) ? (int) $row->news_id : null,
                'comments_enabled' => false,
            ];

            if ($dryRun) {
                $this->line('[dry-run] Would insert: ' . $payload['title'] . ' (' . ($payload['published_at'] ?? 'no-date') . ')');
                continue;
            }

            try {
                NewsArticle::create($payload);
                $created++;
            } catch (\Throwable $e) {
                $this->error('Failed to insert legacy article ' . ($row->news_id ?? '?') . ': ' . $e->getMessage());
                Log::error('import-legacy: insert failed', ['exception' => $e, 'row' => $row]);
            }
        }

        $this->info(sprintf('Done. Created %d articles (dry-run=%s).', $created, $dryRun ? 'yes' : 'no'));
        return 0;
    }
}
