<?php

namespace Shm\ShmChat\ShmChatBlueprints;

use Shm\Shm;
use Shm\ShmAuth\Auth;
use Shm\ShmChat\Classes\ChatMember;
use Shm\ShmChat\Classes\ListQueryInput;
use Shm\ShmChat\Classes\SendMessageInput;
use Shm\ShmChat\SchemaChat\ShmChannelMessages;
use Shm\ShmChat\SchemaChat\ShmChannels;
use Shm\ShmChat\SchemaChat\ShmFastAnswers;
use Shm\ShmChat\ShmChatService;
use Shm\ShmDB\mDB;
use Shm\ShmRPC\ShmRPC;
use Shm\ShmUtils\I18n;

class ShmChatBlueprintsClientRPC extends ShmChatBlueprintsBaseRPC
{


    public static function init(array $authStructures = [])
    {


        $methods =  [

            "auth" => ShmRPC::auth()->email()->auth($authStructures),

            'mode' => ShmRPC::lazy(function () use ($authStructures) {
                return [
                    'type' => Shm::enum(["widget", "full"]),
                    'resolve' => function ($rootValue, array $args)  use ($authStructures) {

                        if (count($authStructures) > 0) {
                            return 'full';
                        }

                        return 'widget';
                    }
                ];
            }),

            'profileID' => ShmRPC::lazy(function () {
                return [
                    'type' => Shm::string(),
                    'resolve' => function ($rootValue, array $args) {

                        Auth::authenticateOrThrow();

                        return (string) Auth::getAuthID();
                    }
                ];
            }),

            'channelInfo' => ShmRPC::lazy(function () {

                return [

                    'type' =>  ShmChannels::structure(),

                    'args' => Shm::structure([
                        'channel' => Shm::ID(),

                    ]),
                    'resolve' => function ($rootValue, array $args) {


                        if (!isset($args['channel'])) {
                            Shm::error(I18n::get('channel_not_found'));
                        }


                        self::accessValidator($args['channel']);

                        return self::runChat(function () use ($args) {
                            return ShmChatService::requireChannel($args['channel']);
                        });
                    }
                ];
            }),

            'joinChannel' => ShmRPC::lazy(function () {
                return [
                    'type' => Shm::bool(),
                    'args' => [
                        "channel" =>  Shm::nonNull(Shm::ID()),
                    ],
                    'resolve' => function ($rootValue, array $args) {
                        Auth::authenticateOrThrow();

                        self::accessValidator($args['channel']);

                        return self::runChat(function () use ($args) {
                            return ShmChatService::addMember($args['channel'], ChatMember::fromAuth());
                        });
                    }
                ];
            }),


            'joinChannelList' => ShmRPC::lazy(function () {
                return [
                    'type' => Shm::structure([
                        'data' => Shm::arrayOf(ShmChannels::structure()),
                        'hash' => Shm::string()
                    ]),
                    'args' => [
                        "limit" => Shm::int()->default(50)->title("Количество сообщений"),
                        "offset" => Shm::int()->default(0)->title("Смещение"),
                        "onlyHash" => Shm::bool()->default(false)->title("Только хэш"),
                    ],
                    'resolve' => function ($rootValue, array $args) {
                        Auth::authenticateOrThrow();

                        return self::runChat(function () use ($args) {
                            return ShmChatService::listJoinableChannels(
                                ListQueryInput::fromRpcArgs($args),
                            );
                        });
                    }
                ];
            }),



            'fastAnswers' => ShmRPC::lazy(function () {
                return [
                    'type' => Shm::arrayOf(ShmFastAnswers::structure()),
                    'resolve' => function ($rootValue, array $args) {
                        Auth::authenticateOrThrow();

                        return ShmFastAnswers::find([
                            'owner' => Auth::getAuthID(),
                            'ownerCollection' => Auth::getAuthCollection(),
                        ]);
                    }
                ];
            }),
            'mFastAnswers' => ShmRPC::lazy(function () {
                return [
                    'type' => Shm::bool(),
                    'args' => [
                        'id' => Shm::ID(),
                        'delete' => Shm::bool()->title("Удалить"),
                        'name' => Shm::string()->title("Название"),
                        'text' => Shm::string()->title("Текст"),
                    ],
                    'resolve' => function ($rootValue, array $args) {
                        Auth::authenticateOrThrow();

                        if (isset($args['id'])) {

                            $delete = $args['delete'] ?? false;
                            if ($delete) {
                                ShmFastAnswers::structure()->deleteOne([
                                    '_id' => mDB::id($args['id']),
                                    'owner' => Auth::getAuthID(),
                                    'ownerCollection' => Auth::getAuthCollection(),
                                ]);
                                return true;
                            }

                            $name = $args['name'] ?? '';
                            $text = $args['text'] ?? '';

                            $set = [];

                            if ($name) {
                                $set['name'] = $name;
                            }
                            if ($text) {
                                $set['text'] = $text;
                            }

                            if (count($set) > 0) {
                                ShmFastAnswers::structure()->updateOne([
                                    '_id' => mDB::id($args['id']),
                                    'owner' => Auth::getAuthID(),
                                    'ownerCollection' => Auth::getAuthCollection(),
                                ], ['$set' => $set]);
                            }

                            return true;
                        } else {

                            $name = $args['name'] ?? '';
                            $text = $args['text'] ?? '';

                            if (!$name || !$text) {
                                Shm::error(I18n::get('name_and_text_are_required'));
                            }

                            $insert = ShmFastAnswers::structure()->insertOne([
                                'owner' => Auth::getAuthID(),
                                'ownerCollection' => Auth::getAuthCollection(),
                                'name' => $name,
                                'text' => $text,
                            ]);

                            return true;
                        }
                    }
                ];
            }),

            'channelList' => ShmRPC::lazy(function () {
                return [
                    'type' => Shm::structure([
                        'data' => Shm::arrayOf(ShmChannels::structure()),
                        'hash' => Shm::string()
                    ]),
                    'args' => [
                        "limit" => Shm::int()->default(50)->title("Количество сообщений"),
                        "offset" => Shm::int()->default(0)->title("Смещение"),
                        "onlyHash" => Shm::bool()->default(false)->title("Только хэш"),
                    ],
                    'resolve' => function ($rootValue, array $args) {
                        Auth::authenticateOrThrow();

                        return self::runChat(function () use ($args) {
                            return ShmChatService::listChannelsForMember(
                                ChatMember::fromAuth(),
                                ListQueryInput::fromRpcArgs($args),
                            );
                        });
                    }
                ];
            }),
            'channelSendMessage' => ShmRPC::lazy(function () {
                return [

                    'type' => ShmChannelMessages::structure(),
                    'args' => [
                        'clientMessageId' => Shm::string(),
                        "channel" => Shm::nonNull(Shm::ID()),
                        'reply' => Shm::ID(),
                        "text" => Shm::string()->title("Текст сообщения"),
                        "attachments" => Shm::arrayOf(Shm::fileDocument())->title("Вложения"),
                        'voice' => Shm::fileAudio(),
                        "payload" => Shm::structure([
                            '*' => Shm::mixed()
                        ]),
                    ],
                    'resolve' => function ($rootValue, $args) {

                        self::accessValidator($args['channel']);

                        return self::runChat(function () use ($args) {
                            return ShmChatService::sendMessage(new SendMessageInput(
                                channelId: (string) $args['channel'],
                                sender: ChatMember::fromAuth(),
                                text: $args['text'] ?? '',
                                reply: isset($args['reply']) ? (string) $args['reply'] : null,
                                attachments: $args['attachments'] ?? [],
                                voice: $args['voice'] ?? null,
                                payload: $args['payload'] ?? null,
                                clientMessageId: $args['clientMessageId'] ?? null,
                            ));
                        });
                    },


                ];
            }),




            'channelClose' => ShmRPC::lazy(function () {
                return [
                    'type' => Shm::bool(),
                    'args' => [
                        "channel" => Shm::ID(),
                    ],
                    'resolve' => function ($rootValue, array $args) {
                        self::accessValidator($args['channel']);

                        return self::runChat(function () use ($args) {
                            return ShmChatService::closeChannel($args['channel'], ChatMember::fromAuth());
                        });
                    }
                ];
            }),


            'channelMarkRead' => ShmRPC::lazy(function () {
                return [
                    'type' => Shm::bool(),
                    'args' => [
                        'channel' => Shm::nonNull(Shm::ID()),
                        'lastReadMessageId' => Shm::ID(),
                    ],
                    'resolve' => function ($rootValue, array $args) {
                        self::accessValidator($args['channel']);

                        return self::runChat(function () use ($args) {
                            ShmChatService::markRead(
                                $args['channel'],
                                ChatMember::fromAuth(),
                                isset($args['lastReadMessageId']) ? (string) $args['lastReadMessageId'] : null,
                            );

                            return true;
                        });
                    },
                ];
            }),

            'channelMessages' => ShmRPC::lazy(function () {
                return [
                    'type' => Shm::structure([
                        'data' => Shm::arrayOf(ShmChannelMessages::structure()),
                        'hash' => Shm::string()
                    ]),
                    'args' => [
                        "channel" => Shm::string(),
                        "limit" => Shm::int()->default(50)->title("Количество сообщений"),
                        "offset" => Shm::int()->default(0)->title("Смещение"),
                        "onlyHash" => Shm::bool()->default(false)->title("Только хэш"),
                    ],
                    'resolve' => function ($rootValue, array $args) {


                        if (!isset($args['channel'])) {
                            Shm::error(I18n::get('channel_not_found'));
                        }

                        self::accessValidator($args['channel']);

                        return self::runChat(function () use ($args) {
                            return ShmChatService::listMessages(
                                $args['channel'],
                                ListQueryInput::fromRpcArgs($args),
                            );
                        });
                    }
                ];
            }),

            'pinnedMessage' => ShmRPC::lazy(
                function () {
                    return [
                        'type' => Shm::bool(),
                        'args' => [
                            "message" => Shm::ID(),
                        ],
                        'resolve' => function ($rootValue, array $args) {
                            if (!isset($args['message'])) {
                                Shm::error(I18n::get('message_not_found'));
                            }

                            return self::runChat(function () use ($args) {
                                return ShmChatService::togglePinnedMessage(
                                    $args['message'],
                                    ChatMember::fromAuth(),
                                );
                            });
                        }
                    ];
                }
            ),
            'channelReaction' => ShmRPC::lazy(function () {
                return [
                    'type' => Shm::bool(),
                    'args' => [
                        "message" => Shm::ID(),
                        "channel" => Shm::ID(),
                        "reaction" => Shm::enum([
                            "heart" => "Сердце",
                            "like" => "Нравится",
                            "laugh" => "Смех",
                            "wow" => "Удивление",
                            "sad" => "Грусть",
                            "angry" => "Злость",
                            "clap" => "Аплодисменты",
                            "party" => "Праздник",
                            "poop" => "Какахa",
                            "fire" => "Огонь"
                        ])
                    ],
                    'resolve' => function ($rootValue, array $args) {

                        if (!isset($args['channel']) || !isset($args['message']) || !isset($args['reaction'])) {
                            Shm::error(I18n::get('channel_message_reaction_not_found'));
                        }

                        return self::runChat(function () use ($args) {
                            return ShmChatService::toggleReaction(
                                $args['channel'],
                                $args['message'],
                                $args['reaction'],
                                ChatMember::fromAuth(),
                            );
                        });
                    }
                ];
            }),



            'channelDeleteMessage' => ShmRPC::lazy(function () {
                return [
                    'type' => Shm::bool(),
                    'args' => [
                        "channel" => Shm::ID(),
                        "message" => Shm::ID(),
                    ],
                    'resolve' => function ($rootValue, array $args) {
                        if (!isset($args['channel']) || !isset($args['message'])) {
                            Shm::error(I18n::get('channel_or_message_not_found'));
                        }

                        self::accessValidator($args['channel']);

                        return self::runChat(function () use ($args) {
                            return ShmChatService::deleteMessage(
                                $args['channel'],
                                $args['message'],
                                ChatMember::fromAuth(),
                            );
                        });
                    }
                ];
            }),

            'channelDocumentUpload' => ShmRPC::fileUpload()->document(),
            'channelVoiceUpload' => ShmRPC::fileUpload()->audio(),
        ];




        ShmRPC::init($methods);
    }
}