<?php

namespace HelpGent\App\Providers;

defined( 'ABSPATH' ) || exit;

use HelpGent\WpMVC\Contracts\Provider;
use HelpGent\App\Repositories\ChatMemberRepository;
use HelpGent\App\Repositories\ChatMessageRepository;
use HelpGent\App\DTO\ChatMemberDTO;
use HelpGent\App\DTO\ChatMessageDTO;
use stdClass;

class ChatMemberProvider implements Provider {
    public ChatMemberRepository $repository;

    public ChatMessageRepository $message_repository;

    public function __construct( ChatMemberRepository $repository, ChatMessageRepository $message_repository ) {
        $this->repository         = $repository;
        $this->message_repository = $message_repository;
    }

    public function boot() {
        add_action( 'helpgent_after_store_chat_message', [ $this, 'add_member' ], 20, 1 );
        add_action( 'helpgent_after_delete_chat_message', [ $this, 'maybe_remove_member' ], 20, 1 );
    }

    public function add_member( ChatMessageDTO $message_dto ) {
        $this->repository->create_item(
            ( new ChatMemberDTO() )->set_message_id( $message_dto->get_id() )->set_user_id( $message_dto->get_created_by() ) 
        );
    }

    public function maybe_remove_member( stdClass $message ) {
        if ( $this->message_repository->member_has_message_in_response( $message->created_by, $message->response_id ) ) {
            return;
        }

        $this->repository->delete_item( $message->id, $message->created_by );
    }
}