<?php

namespace PostenBringCheckout\admin\api\handlers;

use Exception;
use PostenBringCheckout\admin\bring\CheckoutApi;
use WP_REST_Request;
use WP_REST_Response;

if ( ! defined( 'ABSPATH' ) ) {
	exit; // Exit if accessed directly.
}

/**
 * Handles address autocomplete suggestions
 */
class AddressHandler {

	/**
	 * @param WP_REST_Request $request
	 *
	 * @return WP_REST_Response
	 * @throws Exception
	 */
	public function get_address_suggestions( WP_REST_Request $request ) {
		$query = $request->get_param( 'query' );
		$country_code = $request->get_param( 'countryCode' );

		try {
			$suggestions = CheckoutApi::get_instance()->get_address_suggestions( $query, $country_code);

			return new WP_REST_Response( $suggestions, 200 );
		} catch ( Exception $exception ) {
			wc_get_logger()->warning( esc_html($exception->getMessage()), array( 'source' => 'posten-bring-checkout' ) );
			return new WP_REST_Response(null, 500);
		}
	}

	/**
	 * @param WP_REST_Request $request
	 *
	 * @return WP_REST_Response
	 * @throws Exception
	 */
	public function get_address_details( WP_REST_Request $request ) {
		$addressId = $request->get_param( 'addressId' );

		try {
			$address = CheckoutApi::get_instance()->get_address( $addressId );

			return new WP_REST_Response( $address, 200 );
		} catch ( Exception $exception ) {
			wc_get_logger()->warning( esc_html($exception->getMessage()), array( 'source' => 'posten-bring-checkout' ) );
			return new WP_REST_Response( null, 500 );
		}
	}
}
