<?php

namespace Inside\DESK\Listeners;

use Illuminate\Contracts\Queue\ShouldQueue;
use Inside\Content\Models\Content;
use Inside\Content\Models\Contents\Comments;
use Inside\Reaction\Events\ReactionUnsubscribedEvent;
use Inside\Reaction\Facades\Reactions;
use Inside\Reaction\Models\Reaction;

/**
 * Inside package content service.
 *
 * @category Class
 * @package  Inside\DESK\Listeners\ReactionSubscribedListener
 * @author   Maecia <technique@maecia.com>
 * @license  http://www.gnu.org/copyleft/gpl.html GNU General Public License
 * @link     http://www.maecia.com/
 */
class ReactionUnsubscribedListener implements ShouldQueue
{
    public function handle(ReactionUnsubscribedEvent $event): void
    {
        $reaction = $event->reaction;

        if ($reaction->type !== 'like') {
            return;
        }

        /** @var Content $content */
        $content = $reaction->reactionable;

        $langcode = data_get($content, 'langcode') === 'fr' ? 'en' : 'fr';

        switch (class_to_type($reaction->reactionable_type)) {
            case 'news':
                $translation = $content->getTranslationIfExists($langcode);

                $this->deleteReaction($translation, $reaction);
                break;
            case 'comments':
                $translation = Comments::query()->where('uuid_source', $content->uuid_source)->where('langcode', $langcode)->first();

                $this->deleteReaction($translation, $reaction);
                break;
        }
    }

    /**
     * @param mixed $model
     * @param mixed $original
     * @return void
     */
    protected function deleteReaction($model, $original): void
    {
        if (!$model || $model->langcode === $original->reactionable->langcode) {
            return;
        }

        if (!Reaction::query()->where('langcode', $model->langcode)->where('reactionable_uuid', $model->uuid)->where('user_uuid', $original->user_uuid)->where('type', 'like')->exists()) {
            return;
        }

        Reactions::delete('like', $model->uuid, $original->user_uuid, $model->langcode);
    }
}
