<?php

namespace Inside\BCLH\Console;

use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use Inside\Content\Models\Contents\Folders;
use Inside\Content\Models\Contents\Rops;
use Inside\Host\Bridge\BridgeContent;
use Log;
use Symfony\Component\Console\Style\SymfonyStyle;

class FixRopsFolders extends Command
{
    /**
     * @var string
     */
    protected $name = 'bclh:fix-rops-folders';

    /*
   * @var string
   */
    protected $signature = 'bclh:fix-rops-folders';

    /**
     * @var string
     */
    protected $description = 'Fix ROPs folders';

    /**
     * Import users
     */
    public function handle(): void
    {
        $bridge = new BridgeContent();
        $rops = Rops::query()->get();
        $count = $rops->count();

        $this->info(sprintf('Processing %d rops', $count));

        /** @var SymfonyStyle $output */
        $output = $this->getOutput();
        $bar = $output->createProgressBar($count);

        $bar->setFormat("%message%\n %current%/%max% [%bar%] %percent:3s%%");

        $time = time();

        $ropsToFix = [];
        foreach ($rops as $rop) {
            if ($rop->sops->count() === 0) {
                $bar->setMessage(sprintf('Skipping ROP %s (%s)', $rop->title, $rop->folders->first()->title));
                $bar->advance();
                continue;
            }

            if ($rop->folders->first()->uuid === $rop->sops->first()->folders->first()->uuid) {
                $bar->setMessage(sprintf('Skipping ROP %s (%s)', $rop->title, $rop->folders->first()->title));
                $bar->advance();
                continue;
            }

            $ropsToFix[] = $rop;
        }

        foreach ($ropsToFix as $rop) {
            $bar->setMessage(sprintf('Fixing folder for ROP %s (%s => %s)', $rop->title, $rop->folders->first()->title, $rop->sops->first()->folders->first()->title));

            DB::table('inside_pivots')->where('parent_uuid', $rop->uuid)->where('related_field', 'folders')->delete();
            DB::table('inside_pivots')->insert([
                'parent_uuid' => $rop->uuid,
                'related_uuid' => $rop->sops->first()->folders->first()->uuid,
                'weight' => 0,
                'parent_type' => Rops::class,
                'parent_langcode' => $rop->langcode,
                'related_type' => Folders::class,
                'related_langcode' => $rop->langcode,
                'related_field' => 'folders',
            ]);

            $bar->advance();
        }

        $bar->finish();

        $this->info("\nAll rops folders have been fixed.");
    }
}
