<?php

namespace Tests\Tenant;

use App\Jobs\WordPressArticleImport;
use App\Jobs\WordPressBlogImport;
use Illuminate\Http\UploadedFile;
use Illuminate\Support\Facades\Bus;
use Illuminate\Support\Facades\Storage;
use Mtc\ContentManager\Contracts\PageModel;
use Mtc\ContentManager\Models\ContentCategory;
use Mtc\MercuryDataModels\Template;
use Tests\TenantTestCase;
use Tests\UserForTenant;

class BlogImportTest extends TenantTestCase
{
    use UserForTenant;

    private string $xmlPath;

    protected function setUp(): void
    {
        parent::setUp();
        $this->xmlPath = dirname(__DIR__) . '/data/wordpress-blog-export.xml';
    }

    // -------------------------------------------------------
    // Controller tests
    // -------------------------------------------------------

    public function testImportDispatchesBlogImportJob()
    {
        Bus::fake();
        Storage::fake('file-storage');
        Template::factory()->create(['slug' => 'blog-article']);

        $response = $this->actingAs($this->getUser())
            ->withHeader('X-Tenant', tenant('id'))
            ->postJson(route('tenant.blog.import'), [
                'file' => UploadedFile::fake()->createWithContent(
                    'blog-export.xml',
                    file_get_contents($this->xmlPath)
                ),
            ]);

        $response->assertStatus(200);
        $response->assertJson([
            'success' => true,
            'message' => 'Blog import has been queued for processing.',
        ]);

        Bus::assertDispatched(WordPressBlogImport::class, 1);
    }

    public function testImportStoresFileAndCreatesBulkImportLog()
    {
        Bus::fake();
        Storage::fake('file-storage');
        Template::factory()->create(['slug' => 'blog-article']);

        $this->actingAs($this->getUser())
            ->withHeader('X-Tenant', tenant('id'))
            ->postJson(route('tenant.blog.import'), [
                'file' => UploadedFile::fake()->createWithContent(
                    'blog-export.xml',
                    file_get_contents($this->xmlPath)
                ),
            ]);

        // Verify file was stored
        $files = Storage::disk('file-storage')->allFiles('blog-import');
        $this->assertCount(1, $files);
        $this->assertStringStartsWith('blog-import/blog-import-', $files[0]);
        $this->assertStringEndsWith('.xml', $files[0]);

        // Verify BulkImportLog was created
        $this->assertDatabaseHas('bulk_import_log', [
            'object_type' => 'blog',
        ]);
    }

    public function testImportFailsWithoutTemplate()
    {
        Bus::fake();
        Storage::fake('file-storage');
        // Deliberately not creating a blog-article template

        $response = $this->actingAs($this->getUser())
            ->withHeader('X-Tenant', tenant('id'))
            ->postJson(route('tenant.blog.import'), [
                'file' => UploadedFile::fake()->createWithContent(
                    'blog-export.xml',
                    file_get_contents($this->xmlPath)
                ),
            ]);

        $response->assertStatus(200);
        $response->assertJson([
            'success' => false,
            'message' => 'Template "blog-article" not found. Please create the template before importing.',
        ]);

        Bus::assertNotDispatched(WordPressBlogImport::class);
    }

    public function testImportFailsWithInvalidXml()
    {
        Bus::fake();
        Storage::fake('file-storage');
        Template::factory()->create(['slug' => 'blog-article']);

        $response = $this->actingAs($this->getUser())
            ->withHeader('X-Tenant', tenant('id'))
            ->postJson(route('tenant.blog.import'), [
                'file' => UploadedFile::fake()->createWithContent(
                    'invalid.xml',
                    'this is not valid xml'
                ),
            ]);

        $response->assertStatus(200);
        $response->assertJson([
            'success' => false,
            'message' => 'Failed to parse the XML file. Please check the file is valid WordPress export XML.',
        ]);

        Bus::assertNotDispatched(WordPressBlogImport::class);
    }

    public function testImportValidationRequiresFile()
    {
        $response = $this->actingAs($this->getUser())
            ->withHeader('X-Tenant', tenant('id'))
            ->postJson(route('tenant.blog.import'), []);

        $response->assertStatus(422);
    }

    // -------------------------------------------------------
    // WordPressBlogImport job tests
    // -------------------------------------------------------

    public function testJobDispatchesArticleImportsForPublishedPosts()
    {
        Bus::fake([WordPressArticleImport::class]);
        Storage::fake('file-storage');
        Template::factory()->create(['slug' => 'blog-article']);

        $filePath = 'blog-import/test-import.xml';
        Storage::disk('file-storage')->put($filePath, file_get_contents($this->xmlPath));

        $job = new WordPressBlogImport($filePath);
        $job->handle();

        Bus::assertDispatched(WordPressArticleImport::class, 3);
    }

    public function testJobSkipsDraftsAndNonPostItems()
    {
        Bus::fake([WordPressArticleImport::class]);
        Storage::fake('file-storage');
        Template::factory()->create(['slug' => 'blog-article']);

        $filePath = 'blog-import/test-import.xml';
        Storage::disk('file-storage')->put($filePath, file_get_contents($this->xmlPath));

        $job = new WordPressBlogImport($filePath);
        $job->handle();

        // XML contains: 3 published posts, 1 draft, 1 page, 2 attachments
        // Only the 3 published posts should be dispatched
        Bus::assertDispatched(WordPressArticleImport::class, 3);

        // Verify the dispatched jobs have correct post data
        $dispatchedSlugs = [];
        Bus::assertDispatched(WordPressArticleImport::class, function (WordPressArticleImport $job) use (&$dispatchedSlugs) {
            $reflection = new \ReflectionClass($job);
            $property = $reflection->getProperty('postData');
            $property->setAccessible(true);
            $postData = $property->getValue($job);
            $dispatchedSlugs[] = $postData['slug'];
            return true;
        });

        $this->assertContains('first-blog-post', $dispatchedSlugs);
        $this->assertContains('second-blog-post', $dispatchedSlugs);
        $this->assertContains('third-blog-post', $dispatchedSlugs);
        $this->assertNotContains('draft-post', $dispatchedSlugs);
        $this->assertNotContains('about-us', $dispatchedSlugs);
    }

    public function testJobResolvesFeaturedImageFromAttachments()
    {
        Bus::fake([WordPressArticleImport::class]);
        Storage::fake('file-storage');
        Template::factory()->create(['slug' => 'blog-article']);

        $filePath = 'blog-import/test-import.xml';
        Storage::disk('file-storage')->put($filePath, file_get_contents($this->xmlPath));

        $job = new WordPressBlogImport($filePath);
        $job->handle();

        // Check that the first post job has the correct featured image URL
        Bus::assertDispatched(WordPressArticleImport::class, function (WordPressArticleImport $job) {
            $reflection = new \ReflectionClass($job);

            $postDataProp = $reflection->getProperty('postData');
            $postDataProp->setAccessible(true);
            $postData = $postDataProp->getValue($job);

            $imageProp = $reflection->getProperty('featuredImageUrl');
            $imageProp->setAccessible(true);
            $featuredImageUrl = $imageProp->getValue($job);

            if ($postData['slug'] === 'first-blog-post') {
                return $featuredImageUrl === 'https://example.com/wp-content/uploads/2024/01/featured-one.jpg';
            }

            if ($postData['slug'] === 'second-blog-post') {
                return $featuredImageUrl === 'https://example.com/wp-content/uploads/2024/02/featured-two.jpg';
            }

            if ($postData['slug'] === 'third-blog-post') {
                return $featuredImageUrl === null;
            }

            return true;
        });
    }

    public function testJobExtractsCorrectPostData()
    {
        Bus::fake([WordPressArticleImport::class]);
        Storage::fake('file-storage');
        Template::factory()->create(['slug' => 'blog-article']);

        $filePath = 'blog-import/test-import.xml';
        Storage::disk('file-storage')->put($filePath, file_get_contents($this->xmlPath));

        $job = new WordPressBlogImport($filePath);
        $job->handle();

        Bus::assertDispatched(WordPressArticleImport::class, function (WordPressArticleImport $job) {
            $reflection = new \ReflectionClass($job);

            $postDataProp = $reflection->getProperty('postData');
            $postDataProp->setAccessible(true);
            $postData = $postDataProp->getValue($job);

            if ($postData['slug'] !== 'first-blog-post') {
                return true;
            }

            return $postData['title'] === 'First Blog Post'
                && $postData['date'] === '2024-01-15 10:30:00'
                && str_contains($postData['content'], 'first blog post content')
                && $postData['excerpt'] === 'This is the excerpt for the first post.';
        });
    }

    public function testJobHandlesEmptyXmlWithNoPublishedPosts()
    {
        Bus::fake([WordPressArticleImport::class]);
        Storage::fake('file-storage');
        Template::factory()->create(['slug' => 'blog-article']);

        $emptyXml = '<?xml version="1.0" encoding="UTF-8" ?>
        <rss version="2.0"
            xmlns:excerpt="http://wordpress.org/export/1.2/excerpt/"
            xmlns:content="http://purl.org/rss/1.0/modules/content/"
            xmlns:dc="http://purl.org/dc/elements/1.1/"
            xmlns:wp="http://wordpress.org/export/1.2/"
        >
        <channel>
            <title>Empty Blog</title>
            <item>
                <title>Draft Only</title>
                <wp:post_id>1</wp:post_id>
                <wp:post_name>draft-only</wp:post_name>
                <wp:post_date>2024-01-01 00:00:00</wp:post_date>
                <wp:post_type>post</wp:post_type>
                <wp:status>draft</wp:status>
                <content:encoded><![CDATA[<p>Draft content</p>]]></content:encoded>
                <excerpt:encoded><![CDATA[]]></excerpt:encoded>
            </item>
        </channel>
        </rss>';

        $filePath = 'blog-import/test-empty.xml';
        Storage::disk('file-storage')->put($filePath, $emptyXml);

        $job = new WordPressBlogImport($filePath);
        $job->handle();

        Bus::assertNotDispatched(WordPressArticleImport::class);
    }

    public function testJobExtractsCategoriesFromXml()
    {
        Bus::fake([WordPressArticleImport::class]);
        Storage::fake('file-storage');
        Template::factory()->create(['slug' => 'blog-article']);

        $filePath = 'blog-import/test-import.xml';
        Storage::disk('file-storage')->put($filePath, file_get_contents($this->xmlPath));

        $job = new WordPressBlogImport($filePath);
        $job->handle();

        $dispatched = [];
        Bus::assertDispatched(WordPressArticleImport::class, function (WordPressArticleImport $job) use (&$dispatched) {
            $reflection = new \ReflectionClass($job);

            $postDataProp = $reflection->getProperty('postData');
            $postDataProp->setAccessible(true);
            $slug = $postDataProp->getValue($job)['slug'];

            $categoriesProp = $reflection->getProperty('categories');
            $categoriesProp->setAccessible(true);
            $dispatched[$slug] = $categoriesProp->getValue($job);

            return true;
        });

        // First post has two categories (post_tag "Featured" should be excluded)
        $this->assertCount(2, $dispatched['first-blog-post']);
        $this->assertEquals('news', $dispatched['first-blog-post'][0]['slug']);
        $this->assertEquals('News', $dispatched['first-blog-post'][0]['name']);
        $this->assertEquals('motorhome-holidays', $dispatched['first-blog-post'][1]['slug']);
        $this->assertEquals('Motorhome Holidays', $dispatched['first-blog-post'][1]['name']);

        // Second post has one category
        $this->assertCount(1, $dispatched['second-blog-post']);
        $this->assertEquals('road-trips', $dispatched['second-blog-post'][0]['slug']);
        $this->assertEquals('Road Trips', $dispatched['second-blog-post'][0]['name']);

        // Third post has no categories
        $this->assertEmpty($dispatched['third-blog-post']);
    }

    public function testArticleImportCreatesCategoriesAndSyncsToPage()
    {
        Template::factory()->create(['slug' => 'blog-article']);

        $postData = [
            'title' => 'Test Post With Categories',
            'slug' => 'test-post-with-categories',
            'date' => '2024-01-15 10:30:00',
            'content' => '<p>Test content.</p>',
            'excerpt' => 'Test excerpt.',
            'seo_title' => null,
            'seo_description' => null,
        ];

        $categories = [
            ['slug' => 'motorhome-holidays', 'name' => 'Motorhome Holidays'],
            ['slug' => 'road-trips', 'name' => 'Road Trips'],
        ];

        $job = new WordPressArticleImport($postData, null, 'blog-article', $categories);
        $job->handle();

        // Assert content_categories were created
        $this->assertDatabaseHas('content_categories', ['slug' => 'motorhome-holidays', 'name' => 'Motorhome Holidays']);
        $this->assertDatabaseHas('content_categories', ['slug' => 'road-trips', 'name' => 'Road Trips']);

        // Assert the page was linked to both categories via the pivot table
        $page = app(PageModel::class)->where('slug', 'test-post-with-categories')->first();
        $this->assertNotNull($page);
        $this->assertCount(2, $page->categories);
        $this->assertEquals(
            ['motorhome-holidays', 'road-trips'],
            $page->categories->pluck('slug')->sort()->values()->toArray()
        );
    }

    public function testArticleImportDoesNotDuplicateExistingCategories()
    {
        Template::factory()->create(['slug' => 'blog-article']);

        // Pre-create a category
        ContentCategory::create(['slug' => 'road-trips', 'name' => 'Road Trips']);

        $postData = [
            'title' => 'Another Post',
            'slug' => 'another-post',
            'date' => '2024-02-01 12:00:00',
            'content' => '<p>Content.</p>',
            'excerpt' => '',
            'seo_title' => null,
            'seo_description' => null,
        ];

        $categories = [
            ['slug' => 'road-trips', 'name' => 'Road Trips'],
            ['slug' => 'news', 'name' => 'News'],
        ];

        $job = new WordPressArticleImport($postData, null, 'blog-article', $categories);
        $job->handle();

        // Should still only have one "road-trips" category, not a duplicate
        $this->assertEquals(1, ContentCategory::where('slug', 'road-trips')->count());

        // But "news" should have been created
        $this->assertDatabaseHas('content_categories', ['slug' => 'news', 'name' => 'News']);

        // Page should be linked to both
        $page = app(PageModel::class)->where('slug', 'another-post')->first();
        $this->assertCount(2, $page->categories);
    }

    public function testArticleImportWithNoCategoriesCreatesNoPivotRows()
    {
        Template::factory()->create(['slug' => 'blog-article']);

        $postData = [
            'title' => 'No Categories Post',
            'slug' => 'no-categories-post',
            'date' => '2024-03-01 09:00:00',
            'content' => '<p>Content.</p>',
            'excerpt' => '',
            'seo_title' => null,
            'seo_description' => null,
        ];

        $job = new WordPressArticleImport($postData, null, 'blog-article', []);
        $job->handle();

        $page = app(PageModel::class)->where('slug', 'no-categories-post')->first();
        $this->assertNotNull($page);
        $this->assertCount(0, $page->categories);
    }

    public function testJobDeletesFileAfterProcessing()
    {
        Bus::fake([WordPressArticleImport::class]);
        Storage::fake('file-storage');
        Template::factory()->create(['slug' => 'blog-article']);

        $filePath = 'blog-import/test-import.xml';
        Storage::disk('file-storage')->put($filePath, file_get_contents($this->xmlPath));

        $this->assertTrue(Storage::disk('file-storage')->exists($filePath));

        $job = new WordPressBlogImport($filePath);
        $job->handle();

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