<?php

namespace PostenBringCheckout\admin\api\handlers;

use Exception;
use PostenBringCheckout\Admin\Bring\CredentialsService;
use PostenBringCheckout\Admin\Bring\CheckoutApi;
use WP_REST_Request;
use WP_REST_Response;

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

/**
 * Credentials handler
 *
 * Handler responsible for fetching and storing credentials
 *
 * @since 0.0.1
 */
class CredentialsHandler {


	/**
	 * Get credentials.
	 *
	 * @return WP_REST_Response response.
	 * @since 0.0.1
	 */
	public function get_credentials(): WP_REST_Response {
		$data = CredentialsService::get_instance()->get_credentials_and_webshop_id();

		$response = new WP_REST_Response( $data->to_array() );
		$response->set_status( 200 );
		$response->header( 'Content-Type', 'application/json' );

		return $response;
	}

	/**
	 * Get credentials.
	 *
	 * @param WP_REST_Request $request Request.
	 *
	 * @return WP_REST_Response response.
	 * @since 0.0.1
	 */
	public function store_credentials( WP_REST_Request $request ): WP_REST_Response {
		$params     = $request->get_json_params();
		$api_key    = isset( $params['apikey'] ) ? $params['apikey'] : null;
		$webshop_id = isset( $params['webshop_id'] ) ? $params['webshop_id'] : null;

		if ( null === $api_key || null === $webshop_id ) {
			return new WP_REST_Response(
				array(
					'validCredentials' => false,
					'validWebshopId'   => false,
					'accessToWebshop'  => false,
				),
				400
			);
		}

		try {
			$validationResult = CheckoutApi::get_instance()->verifyCredentials( $api_key, $webshop_id );
		} catch ( Exception $e ) {
			wc_get_logger()->warning( 'Error occurred while validating the credentials: ' . esc_html($e->getMessage()), array( 'source' => 'posten-bring-checkout' ) );

			return new WP_REST_Response( array( 'error' => esc_html($e->getMessage()) ), 500 );
		}
		if ( $validationResult->isInvalid() ) {
			$response = new WP_REST_Response(
				array(
					'validCredentials' => $validationResult->validCredentials,
					'validWebshopId'   => $validationResult->validWebshopId,
					'accessToWebshop'  => $validationResult->accessToWebshop,
				),
				200
			);
		} else {
			try {
				CheckoutApi::get_instance()->installWebshop( $api_key, $webshop_id );
			} catch ( Exception $e ) {
				wc_get_logger()->warning( 'Error occurred while installing the webshop: ' . esc_html($e->getMessage()), array( 'source' => 'posten-bring-checkout' ) );

				return new WP_REST_Response( array( 'error' => esc_html($e->getMessage()) ), 500 );
			}
			CredentialsService::get_instance()->add_or_update_credentials_and_webshop_id( $api_key, $webshop_id );
			$response = new WP_REST_Response(
				array(
					'validCredentials' => true,
					'validWebshopId'   => true,
					'accessToWebshop'  => true,
				),
				200
			);
		}

		$response->header( 'Content-Type', 'application/json' );

		return $response;
	}
}
