<?php

namespace App\Jobs;

use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use App\Facades\Settings;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Storage;
use Mtc\MercuryDataModels\Template;

class WordPressBlogImport implements ShouldQueue
{
    use Dispatchable;
    use InteractsWithQueue;
    use Queueable;
    use SerializesModels;

    public int $timeout = 600;

    public function __construct(
        private readonly string $filePath,
    ) {
        //
    }

    public function handle(): void
    {
        $templateId = Settings::get('app-content-blog-default-template');
        $template = $templateId
            ? Template::query()->find($templateId)
            : Template::query()->where('slug', 'blog-article')->first();

        if (!$template) {
            Log::error('WordPressBlogImport: No blog template found '
                . '(checked setting "app-content-blog-default-template" and slug "blog-article")');
            return;
        }

        $xmlContent = Storage::disk('file-storage')->get($this->filePath);

        if (!$xmlContent) {
            Log::error('WordPressBlogImport: File not found', ['path' => $this->filePath]);
            return;
        }

        $xml = simplexml_load_string($xmlContent, 'SimpleXMLElement', LIBXML_NOCDATA);

        if ($xml === false) {
            Log::error('WordPressBlogImport: Failed to parse XML', ['path' => $this->filePath]);
            return;
        }

        $wpNamespace = 'http://wordpress.org/export/1.2/';
        $contentNamespace = 'http://purl.org/rss/1.0/modules/content/';
        $excerptNamespace = 'http://wordpress.org/export/1.2/excerpt/';

        // Build attachments map (post_id -> attachment_url)
        $attachments = [];
        foreach ($xml->channel->item as $item) {
            $wp = $item->children($wpNamespace);
            if ((string) $wp->post_type === 'attachment') {
                $attachments[(string) $wp->post_id] = (string) $wp->attachment_url;
            }
        }

        $count = 0;
        foreach ($xml->channel->item as $item) {
            $wp = $item->children($wpNamespace);

            if ((string) $wp->post_type !== 'post' || (string) $wp->status !== 'publish') {
                continue;
            }

            $content = $item->children($contentNamespace);
            $excerpt = $item->children($excerptNamespace);

            // Resolve featured image and Yoast SEO data from postmeta
            $featuredImageUrl = null;
            $seoTitle = null;
            $seoDescription = null;
            foreach ($wp->postmeta as $meta) {
                $metaKey = (string) $meta->meta_key;
                if ($metaKey === '_thumbnail_id') {
                    $thumbnailId = (string) $meta->meta_value;
                    if (isset($attachments[$thumbnailId])) {
                        $featuredImageUrl = $attachments[$thumbnailId];
                    }
                } elseif ($metaKey === '_yoast_wpseo_title') {
                    $value = (string) $meta->meta_value;
                    $seoTitle = str_contains($value, '%%') ? null : $value;
                } elseif ($metaKey === '_yoast_wpseo_metadesc') {
                    $seoDescription = (string) $meta->meta_value;
                }
            }

            // Fallback: extract first image from post content if no featured image in postmeta
            if (!$featuredImageUrl) {
                $postContent = (string) $content->encoded;
                if (preg_match('/<img[^>]+src=["\']([^"\']+)["\']/i', $postContent, $matches)) {
                    $featuredImageUrl = $matches[1];
                }
            }

            $categories = [];
            foreach ($item->category as $cat) {
                $attrs = $cat->attributes();
                if ((string) ($attrs['domain'] ?? '') === 'category') {
                    $categories[] = [
                        'slug' => (string) $attrs['nicename'] ?? '',
                        'name' => (string) $cat ?? '',
                    ];
                }
            }

            $slug = null;
            $link = (string) $item->link;
            if ($link) {
                $urlPath = rtrim(parse_url($link, PHP_URL_PATH) ?? '', '/');
                $slug = basename($urlPath) ?: null;
            }
            if (empty($slug)) {
                $slug = \Illuminate\Support\Str::slug((string) $item->title);
            }

            $postData = [
                'title' => (string) $item->title,
                'slug' => $slug,
                'date' => (string) $wp->post_date,
                'content' => (string) $content->encoded,
                'excerpt' => (string) $excerpt->encoded,
                'seo_title' => $seoTitle,
                'seo_description' => $seoDescription,
            ];

            WordPressArticleImport::dispatch($postData, $featuredImageUrl, $template->slug, $categories);
            $count++;
        }

        Log::info('WordPressBlogImport: Dispatched ' . $count . ' article import jobs', [
            'path' => $this->filePath,
        ]);

        Storage::disk('file-storage')->delete($this->filePath);
    }
}
