<?php

namespace WPDesk\FakturyKSEF\Api\Exceptions;

use Exception;
use Throwable;
use WPDeskKSEFVendor\GuzzleHttp\Exception\ConnectException;
use WPDeskKSEFVendor\GuzzleHttp\Exception\RequestException;

class KSeFExceptionFactory {

	public static function create( Throwable $e ): Exception {
		if ( $e instanceof ConnectException ) {
			return new KSeFNetworkException( __( 'Network connection error. KSeF might be down or unreachable.', 'ksef-for-flexible-invoices' ), 0, $e );
		}

		if ( $e instanceof RequestException ) {
			if ( $e->hasResponse() ) {
				$status_code = $e->getResponse()->getStatusCode();
				$raw_body    = (string) $e->getResponse()->getBody();
				$data        = json_decode( $raw_body, true );

				if ( $status_code >= 500 ) {
					return new KSeFNetworkException( __( 'Internal server error from KSeF.', 'ksef-for-flexible-invoices' ) . ' ' . $raw_body, $e->getCode(), $e );
				}

				if ( is_array( $data ) ) {
					return new KSeFAPIException( $data, $e->getCode(), $e );
				}

				return new KSeFAPIException( [], $e->getCode(), $e, $raw_body );
			}

			return new KSeFNetworkException( __( 'Network connection error. No response received from KSeF.', 'ksef-for-flexible-invoices' ), 0, $e );
		}

		return new KSeFNetworkException( $e->getMessage(), 0, $e );
	}
}
