<?php

namespace humhub\modules\cgyshare;

use humhub\modules\content\models\Content;
use humhub\modules\post\models\Post;
use humhub\modules\sharebetween\services\ShareService;
use humhub\modules\space\models\Space;
use humhub\modules\user\models\User;
use Yii;
use yii\base\Event;

class Events
{
    /**
     * Automatically shares newly created public profile posts to the configured
     * Main Space. Users are not shown a checkbox, toggle, or share action.
     */
    public static function onPostCreated(Event $event): void
    {
        /** @var Post $post */
        $post = $event->sender;

        try {
            $module = Yii::$app->getModule('cgy-share');
            if (!$module || (int)$module->settings->get('autoShareEnabled', 1) !== 1) {
                return;
            }

            $shareModule = Yii::$app->getModule('sharebetween');
            if (!$shareModule || !$shareModule->isEnabled) {
                Yii::warning('Automatic sharing skipped because the Share content module is unavailable.', 'cgy-share');
                return;
            }

            $content = $post->content;
            if (!$content || !($content->container instanceof User)) {
                return;
            }

            if ((int)$module->settings->get('publicOnly', 1) === 1
                && (int)$content->visibility !== Content::VISIBILITY_PUBLIC) {
                return;
            }

            if (!$content->getStateService()->isPublished()) {
                return;
            }

            $targetSpace = Space::findOne([
                'guid' => $module->settings->get('targetSpaceGuid'),
            ]);

            if (!$targetSpace) {
                Yii::warning('Automatic sharing skipped because no valid Main Space is configured.', 'cgy-share');
                return;
            }

            $sharingUser = $post->content->createdBy ?? Yii::$app->user->getIdentity();
            if (!$sharingUser) {
                Yii::warning('Automatic sharing skipped because the post creator could not be resolved.', 'cgy-share');
                return;
            }

            $service = new ShareService($post, $sharingUser);

            if ($service->exist($targetSpace)) {
                return;
            }

            if (!$service->canCreate($targetSpace)) {
                Yii::warning(
                    'Automatic sharing skipped because the post creator cannot share into the configured Main Space.',
                    'cgy-share'
                );
                return;
            }

            $existingGuids = [];
            foreach ($service->list() as $container) {
                if (!empty($container->guid)) {
                    $existingGuids[] = $container->guid;
                }
            }

            $existingGuids[] = $targetSpace->guid;
            $service->shareOnContainerGuids(array_values(array_unique($existingGuids)));
        } catch (\Throwable $exception) {
            Yii::error(
                'Automatic Main Space sharing failed: ' . $exception->getMessage(),
                'cgy-share'
            );
        }
    }
}
