<?php

namespace App\Jobs;

use App\Traits\TemplateElementSyncProviders;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Mtc\ContentManager\Contracts\ContentElement;
use Mtc\ContentManager\Contracts\ModelWithContent;

class SyncContentAgainstContentElement implements ShouldQueue
{
    use Dispatchable;
    use InteractsWithQueue;
    use Queueable;
    use SerializesModels;
    use TemplateElementSyncProviders;

    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct(private readonly ContentElement $element, private readonly ModelWithContent $model)
    {
        $this->onQueue('sync');
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        $this->loadRelationships();
        $repository = $this->getRepository($this->model);
        if ($repository && !$repository->isContentElementInSync($this->model, $this->element)) {
            $repository->syncElementWithTemplate($this->model->id, $this->element);
        }
    }

    private function loadRelationships()
    {
        if (method_exists($this->model, 'template')) {
            $this->model->load([
                'template.elements.element.fields',
            ]);
        }
        $this->model->load([
            'content.mediaUses.media',
            'content.subContent.mediaUses.media',
            'content.subContent.subContent.mediaUses.media',
            'content.subContent.subContent.subContent.mediaUses.media',
            'content.globalContent.contentElement.fields',
            'content.contentElement.fields',
            'content.subContent.contentElement.fields',
            'content.subContent.subContent.contentElement.fields',
            'content.subContent.subContent.subContent.contentElement.fields',
        ]);
    }
}
