<?php

if ( ! defined( 'ABSPATH' ) ) {
    exit;
}

class Niwa_AI_Admin_Autonomy_Telegram_Authorization {

    /** @var Niwa_AI_Admin_Autonomy_Telegram|null */
    private $telegram;

    /** @var array<string, callable> */
    private $callbacks;

    public function __construct( $telegram = null, $callbacks = array() ) {
        $this->telegram  = $telegram;
        $this->callbacks = is_array( $callbacks ) ? $callbacks : array();
    }

    public function resolve( $message ) {
        $message = is_array( $message ) ? $message : array();
        if ( ! $this->telegram || ! method_exists( $this->telegram, 'get_user_role' ) ) {
            return array(
                'handled' => false,
                'user_role' => 'admin',
            );
        }

        $chat_id   = isset( $message['chat_id'] ) ? (string) $message['chat_id'] : '';
        $user_role = $this->telegram->get_user_role( $chat_id );
        if ( null !== $user_role ) {
            return array(
                'handled'   => false,
                'user_role' => (string) $user_role,
            );
        }

        $intro_result = method_exists( $this->telegram, 'send_unauthorized_introduction' )
            ? (array) $this->telegram->send_unauthorized_introduction( $message )
            : array();
        $this->log(
            'unauthorized_chat_intro',
            array(
                'chat_id' => $chat_id,
                'from_id' => isset( $message['from_id'] ) ? (string) $message['from_id'] : '',
                'sent'    => ! empty( $intro_result['sent'] ),
                'reason'  => isset( $intro_result['reason'] ) ? (string) $intro_result['reason'] : '',
            )
        );

        if ( ! empty( $message['update_id'] ) && method_exists( $this->telegram, 'remember_processed_update' ) ) {
            $this->telegram->remember_processed_update( $message['update_id'] );
        }

        return array(
            'handled' => true,
            'result'  => array(
                'success' => true,
                'ignored' => true,
            ),
        );
    }

    private function log( $event, $context = array() ) {
        Niwa_AI_Admin_Autonomy_Callbacks::call( $this->callbacks, 'debug_logger', array( $event, is_array( $context ) ? $context : array() ) );
    }
}
