<?php

namespace App\Http\Controllers;

use App\Jobs\SyncContentAgainstContentElement;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Foundation\Bus\DispatchesJobs;
use Mtc\MercuryDataModels\ContentElement;
use Mtc\ContentManager\Contracts\ElementRepositoryContract;

class ElementController extends \Mtc\ContentManager\Http\Controllers\ElementController
{
    use DispatchesJobs;

    public function syncUsage(ContentElement $element, ElementRepositoryContract $repository): array
    {
        $job_class = SyncContentAgainstContentElement::class;
        $queries = [
            $element->newCarContent()->with('owner'),
            $element->offerContent()->with('owner'),
            $element->pageElements()->with('owner'),
            $element->templateElements()->with('owner'),
        ];
        foreach ($queries as $query) {
            $query->get()
                ->filter(fn(Model $content) => $content->owner)
                ->each(fn(Model $content) => $this->dispatch(new $job_class($element, $content->owner)));
        }

        $element->globalElements()->get()
            ->each(fn(Model $content) => $this->dispatch(new $job_class($element, $content)));
        return $this->checkUsage($element->id, $repository);
    }
}
