<?php

namespace App\Libs\Services;

use App\Jobs\ProcessSearch;
use App\Libs\Facades\ContentTypes;
use App\Models\Entry;
use App\Models\Website;
use Illuminate\Support\Facades\DB;

class SearchService
{
    public function rebuild(Website $website)
    {
        $languages = $website->languages()->where('is_active', 1)->get();
        $pageContentType = ContentTypes::find('page');

        DB::delete('delete from website_object_search where website_id = ' . $website->id);

        $pages = Entry::full()
            ->where('status', 'published')
            ->orderBy('position', 'asc')
            ->get();

        foreach ($pages as $page) {
            $templateId = $page->template;
            $template = config('backoffice.generic.page.templates.'.$website->id.'.'.$templateId);

            if (!empty($template['view'])) {
                ProcessSearch::dispatch($pageContentType, $page, false, $website->id);
            }

            if (!empty($template['detailContentType'])) {
                $detailType = $template['detailContentType'];
                $contentType = ContentTypes::find($detailType);
                $modelClass = $contentType->getModelType();

                if (!$contentType->isWebsiteSearchable($website->id)) {
                    continue;
                }

                // gets base page lang status to prevent detail pages from appearing in search if base is disabled
                $disabledLanguages = [];
                foreach ($languages as $lang) {
                    $pageWol = $page->websites->findByWebsite($website->id)->languages->findByLocale($lang->id);
                    if ($pageWol->lang_status === 'draft') {
                        $disabledLanguages[] = $lang->id;
                    }
                }

                $q = $modelClass::full()
                    ->where('status', 'published')
                    ->orderBy('position', 'asc');
                $objects = $q->get();

                foreach ($objects as $object) {
                    ProcessSearch::dispatch($contentType, $object, false, $website->id, $disabledLanguages);
                }
            }
        }
    }
}
