<?php

namespace Tests\Tenant;

use App\Jobs\SyncContentToTemplate;
use App\PageRepository;
use Database\Seeders\MercuryTheme\ContentElementSeeder;
use Database\Seeders\MercuryTheme\TemplateSeeder;
use Mtc\ContentManager\Models\Page;
use Mtc\MercuryDataModels\Template;
use Tests\TenantTestCase;

class SyncContentToTemplateJobTest extends TenantTestCase
{
    public function testJobHandlesPageModel()
    {
        $this->seed(ContentElementSeeder::class);
        $this->seed(TemplateSeeder::class);

        $template = Template::query()->first();
        $page = Page::factory()->create([
            'title' => 'Test Page',
            'template_id' => $template?->id,
        ]);

        // Job should run without exception
        (new SyncContentToTemplate($page))->handle();

        $this->assertNotNull($page->fresh());
    }

    public function testJobLoadsRelationships()
    {
        $this->seed(ContentElementSeeder::class);
        $this->seed(TemplateSeeder::class);

        $template = Template::query()->first();
        $page = Page::factory()->create([
            'title' => 'Test Page',
            'template_id' => $template?->id,
        ]);

        (new SyncContentToTemplate($page))->handle();

        // After job execution, the page should still exist
        $this->assertTrue(Page::query()->where('id', $page->id)->exists());
    }

    public function testJobSyncsContentWhenOutOfSync()
    {
        $this->seed(ContentElementSeeder::class);
        $this->seed(TemplateSeeder::class);

        $template = Template::query()->where('slug', 'offers-list')->first();

        if (!$template) {
            $this->markTestSkipped('offers-list template not found');
        }

        $page = Page::factory()->create([
            'title' => 'Test Page',
            'template_id' => $template->id,
        ]);

        // Run job - it will check if content is out of sync and sync if needed
        (new SyncContentToTemplate($page))->handle();

        $this->assertNotNull($page->fresh());
    }
}
