<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use App\Models\GenericBackoffice\WebsiteObject;
use App\Jobs\ProcessSearch;
use App\Facades\ContentTypes;

class GenerateSearch extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'search:generate';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Generate search content';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $websiteObjects = WebsiteObject::select('object_type', 'content_type')
            ->where('status', 'published')
            ->groupBy('object_type', 'content_type')
        ->get();
        foreach ($websiteObjects as $websiteObject) {
            if (class_exists($websiteObject->object_type)) {
                $websiteModels = $websiteObject->object_type::with(['websites' => function ($query) {
                    $query->where('status', 'published');
                }])->get();
                foreach($websiteModels as $model) {
                    $contentType = ContentTypes::find($websiteObject->content_type);

                    if (!empty($contentType->getSearch())) {
                        $this->info('Generating search content for Model ' . $websiteObject->object_type . ' with ID: ' . $model->id);
                        ProcessSearch::dispatch($contentType, $model);
                    }
                }
            }
        }
        $this->info('Search content generator is now complete!');
    }
}
