<?php

namespace HelpGent\App\Providers;

defined( "ABSPATH" ) || exit;

use WP_REST_Request;
use HelpGent\WpMVC\Contracts\Provider;

use HelpGent\App\DTO\ChatMessageDTO;
use HelpGent\App\Repositories\ResponseRepository;
use stdClass;

class ConversationUsageTrackerProvider implements Provider {
    public ResponseRepository $response_repository;

    public function __construct( ResponseRepository $response_repository ) {
        $this->response_repository = $response_repository;
    }

    public function boot() {
        add_action( 'helpgent_after_store_chat_message', [ $this, 'maybe_count_as_conversation' ], 10, 2 );
        add_filter( 'helpgent_response_item', [ $this, 'update_response_item_data' ], 10, 1 );
    }

    public function maybe_count_as_conversation( ChatMessageDTO $message_dto, WP_REST_Request $wp_rest_request ) {
        if ( '1' !== $wp_rest_request->get_param( 'increment_conversation_usage_count' ) ) {
            return;
        }

        $this->response_repository->add_meta( $message_dto->get_response_id(), 'counted_as_conversation', '1' );
    }

    public function update_response_item_data( stdClass $response ): stdClass {
        $meta                              = $this->response_repository->get_meta( $response->id, 'counted_as_conversation' );
        $response->counted_as_conversation = empty( $meta ) || $meta->meta_value !== '1' ? '0' : '1';

        return $response;
    }
}