<?php

namespace Inside\DESK\Console;

use Inside\Console\Command;
use Inside\Content\Models\Contents\Comments;

class FixMissingCommentsCommand extends Command
{
    /**
     * @var string
     */
    protected $name = 'desk:fix-missing-comments';

    /*
   * @var string
   */
    protected $signature = 'desk:fix-missing-comments';

    /**
     * @var string
     */
    protected $description = 'Fix missing comments';

    public function __construct()
    {
        parent::__construct();
    }

    public function handle(): void
    {
        $bridge = new \Inside\Host\Bridge\BridgeContent();

        $duplicates = [];
        $missing = [];

        $result = Comments::query()->get();

        foreach ($result->whereNull('uuid_source') as $comment) {
            $this->info('Setting uuid_source for comment '.$comment->uuid);
            $comment->uuid_source = $comment->uuid_host;
            $comment->saveQuietly();
        }

        foreach ($result->groupBy('created_at') as $comments) {
            if ($comments->count() > 2) {
                $duplicates[] = $comments;
            }
            if ($comments->count() === 1) {
                $missing[] = $comments->first();
            }
        }

        foreach ($duplicates as $group) {
            $original = $group->where('uuid_host', $group->pluck('uuid_source')->first())->first();
            $translate = $group->sortBy('uploaded_at')->where('langcode', '!=', $original->langcode)->first();

            $this->info('Deleting duplicate comments (keeping '.$original->uuid.' and '.$translate->uuid.')');

            $group->whereNotIn('uuid', [$original->uuid, $translate->uuid])->each(
                fn ($comment) => $bridge->contentDelete('comments', $comment->uuid)
            );
        }

        foreach ($missing as $comment) {
            $this->info('Recreating missing comment '.$comment->uuid);

            $bundle = $comment->news->count() > 0 ? 'news' : 'events';

            $content = $comment->{$bundle}->first();

            if (! $content) {
                $this->warn('The comment '.$comment->uuid.' is not attached to any content, skipping.');

                continue;
            }

            $translation = $content->getTranslationIfExists($comment->langcode === 'fr' ? 'en' : 'fr');

            if (!$translation) {
                $this->error('No translation found for the parent content of the comment: '.$comment->uuid);

                continue;
            }

            $pid = null;

            if (! is_null($comment->pid)) {
                $parent = Comments::query()->find($comment->pid);
                $parentTranslation = Comments::query()->where('uuid_source', $parent->uuid_source)->where('langcode', $comment->langcode === 'fr' ? 'en' : 'fr')->first();
                if ($parentTranslation) {
                    $pid = $parentTranslation->uuid;
                }
            }

            $bridge->contentInsert('comments', [
                'bundle' => $bundle,
                $bundle => [$translation->uuid],
                'body' => $comment->body,
                'author' => $comment->author,
                'update_author' => $comment->update_author,
                'file' => $comment->file,
                'uuid_source' => $comment->uuid_source ?? $comment->uuid_host,
                'created_at' => $comment->created_at,
                'pid' => $pid,
            ]);
        }
    }
}
