<?php

namespace Inside\DESK\Listeners;

use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Support\Facades\Log;
use Inside\Content\Events\CommentCreatedEvent;
use Inside\Content\Models\Contents\Comments;
use Inside\Host\Bridge\BridgeContent;

/**
 * Send mails when a new alert is created.
 *
 * @category Class
 * @package  Inside\DESK\Listeners\ContentInsertedListener
 * @author   Maecia <technique@maecia.com>
 * @license  http://www.gnu.org/copyleft/gpl.html GNU General Public License
 * @link     http://www.maecia.com/
 */
class CommentInsertedListener implements ShouldQueue
{
    public function handle(CommentCreatedEvent $event): void
    {
        Log::debug('CommentInsertedListener triggered');

        $comment = $event->comment;

        $uuidSource = $comment->uuid_source ?? $comment->uuid_host;

        if (is_null($comment->uuid_source)) {
            $comment->uuid_source = $comment->uuid_host;
            $comment->saveQuietly();
        }

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

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

        if ($translation) {
            return;
        }

        $bridge = new BridgeContent();

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

        $translation = $comment->{$bundle}->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' => $bundle,
            $bundle => [$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,
        ]);
    }
}
