<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Mtc\ContentManager\Models\ContentElementField;
use Mtc\MercuryDataModels\Tenant;
use Mtc\MercuryDataModels\Content;

class FixWrongContentElementIdsCommand extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'fix:content-element-ids';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Fix content element ids';

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        Tenant::query()->whereNull('suspended_at')->get()->each(function (Tenant $tenant) {
            $this->output->info('Tenant: ' . $tenant->id);
            tenancy()->initialize($tenant);

            Content::query()
                ->with('contentElement')
                ->whereNotNull('element_id')
                ->whereNotNull('parent_id')
                ->get()
                ->reject(fn (Content $content) => $content->slug === $content->contentElement?->slug)
                ->each(function (Content $content) {
                    $field = ContentElementField::query()->find($content->element_id);
                    if ($field && $field?->slug === $content->slug) {
                        $this->output->info(
                            "Setting element id on $content->id : $content->slug for page $content->page_id"
                        );
                        $content->update(['element_id' => $field->child_element_id]);
                    }
                });
        });

        return Command::SUCCESS;
    }
}
