<?php

namespace Limb_Chatbot\Includes\AI_Providers\Claude\Endpoints\File\Handlers;

use Limb_Chatbot\Includes\AI_Providers\Claude\Handlers\Response_Handler;
use Limb_Chatbot\Includes\Exceptions\Error_Codes;
use Limb_Chatbot\Includes\Exceptions\Exception;
use WP_Http;

/**
 * Class Response_Handler
 *
 * Handles responses from Claude Files API endpoints.
 *
 * @package Limb_Chatbot\Includes\AI_Providers\Claude\Endpoints\File
 * @since 1.0.9
 */
class File_Response_Handler extends Response_Handler {

	/**
	 * When true, response bodies will be decoded as associative arrays.
	 *
	 * @var bool|null
	 * @since 1.0.9
	 */
	protected ?bool $body_cast_array = true;

	/**
	 * Defines and decodes the response body.
	 *
	 * @return void
	 * @since 1.0.9
	 */
	public function define_body(): void {
		if ( get_class( $this->http_client ) === WP_Http::class ) {
			$body       = wp_remote_retrieve_body( $this->response );
			$this->body = $this->is_application_json() ? json_decode( $body, $this->body_cast_array ) : $body;
		} else {
			$this->body = null;
		}
	}

	/**
	 * Get file metadata from the response.
	 *
	 * @return array File metadata.
	 * @throws Exception If response is invalid.
	 * @since 1.0.9
	 */
	public function get_file_metadata(): array {
		$body = $this->get_body();

		if ( empty( $body ) || ! is_array( $body ) ) {
			throw new Exception(
				Error_Codes::TECHNICAL_ERROR,
				__( 'Invalid file response from Claude API', 'limb-chatbot' )
			);
		}

		return array(
			'external_id'  => $body['id'] ?? '',
			'filename'     => $body['filename'] ?? '',
			'mime_type'    => $body['mime_type'] ?? '',
			'size_bytes'   => $body['size_bytes'] ?? 0,
			'created_at'   => $body['created_at'] ?? '',
			'type'         => $body['type'] ?? 'file',
			'downloadable' => $body['downloadable'] ?? false,
		);
	}

	/**
	 * Get raw response body (for file downloads).
	 *
	 * @return string Raw body content.
	 * @since 1.0.9
	 */
	public function get_raw_body(): string {
		if ( get_class( $this->http_client ) === WP_Http::class ) {
			return wp_remote_retrieve_body( $this->response );
		}

		return '';
	}

	/**
	 * Get response as array.
	 *
	 * @return array Response body.
	 * @since 1.0.9
	 */
	public function get_body() {
		if ( $this->body === null ) {
			$this->define_body();
		}

		return $this->body;
	}
}
