<?php

namespace HelpGent\App\Repositories;

defined( "ABSPATH" ) || exit;

use HelpGent\App\DTO\ChatMemberDTO;
use HelpGent\App\Models\ChatMember;
use HelpGent\App\Models\ChatMessage;
use HelpGent\WpMVC\Database\Query\Builder;
use HelpGent\WpMVC\Repositories\Repository;
use stdClass;

class ChatMemberRepository extends Repository {
    public function get_query_builder(): Builder {
        return ChatMember::query();
    }

    public function create_item( ChatMemberDTO $dto ) {
        $values               = $dto->to_array();
        $values['created_at'] = helpgent_now();
        return $this->get_query_builder()->insert_get_id( $this->process_values( $values ) );
    }

    public function delete_item( int $message_id, int $user_id ) {
        return $this->get_query_builder()
            ->where( 'message_id', $message_id )
            ->where( 'user_id', $user_id )
            ->delete();
    }

    public function get_member_response_ids( int $user_id ) {
        $members = ChatMember::query( 'member' )
            ->select( [ 'message.response_id' ] )
            ->join( ChatMessage::get_table_name() . ' as message', 'member.message_id', 'message.id' )
            ->where( 'member.user_id', $user_id )
            ->get();

        return array_map( [ $this, 'format_member_response_id_item' ], $members );
    }

    public function format_member_response_id_item( stdClass $item ) {
        return absint( $item->response_id );
    }
}