<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Support\Facades\Schema;
use Inside\Content\Models\Contents\Comments;
use Inside\Host\Bridge\BridgeContent;

class TranslateComments extends Migration
{
    public function up(): void
    {
        if (!Schema::hasColumn('inside_content_comments', 'uuid_source')) {
            return;
        }

        $bridge = new BridgeContent();
        $comments = Comments::query()->where('pid', null)->where('uuid_source', null)->get();

        foreach ($comments as $comment) {
            $this->translateComment($bridge, $comment);
        }

        $children = Comments::query()->whereNotNull('pid')->where('uuid_source', null)->get();

        foreach ($children as $child) {
            $this->translateComment($bridge, $child);
        }
    }

    protected function translateComment(BridgeContent $bridge, Comments $comment): void
    {
        $uuidSource = $comment->uuid_source ?? $comment->uuid_host;

        if (is_null($comment->uuid_source)) {
            $bridge->contentUpdate('comments', [
                'uuid' => $comment->uuid,
                'uuid_source' => $comment->uuid_host,
            ]);
        }

        $langcode = $comment->langcode === 'fr' ? 'en' : 'fr';

        $translation = Comments::query()->where('uuid_source', $uuidSource)->where('langcode', $langcode)->first();

        if ($translation) {
            return;
        }

        if ($comment->news->count() === 0) {
            return;
        }

        $translation = $comment->news->first()->getTranslationIfExists($langcode);

        if (!$translation) {
            return;
        }

        $pid = null;

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

        $bridge->contentInsert('comments', [
            'bundle' => 'news',
            'news' => [$translation->uuid],
            'body' => $comment->body,
            'author' => $comment->author,
            'update_author' => $comment->update_author,
            'file' => $comment->file,
            'uuid_source' => $uuidSource,
            'created_at' => $comment->created_at,
            'pid' => $pid,
            'langcode' => $langcode,
            'status' => 1,
        ]);
    }

    public function down(): void
    {
    }
}
