<?php

namespace Fotogenic_AI;

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

final class Service_Credits {
	public function handle_credits_refresh( \WP_REST_Request $request ) {
		unset( $request );
		$result = Credits_Service::instance()->refresh( 0 );
		if ( is_wp_error( $result ) ) {
			$cached = Credits_Service::instance()->get_status( 0 );
			if ( is_array( $cached ) ) {
				$cached['refreshError'] = true;
				$cached['errorCode']    = sanitize_key( (string) $result->get_error_code() );

				return rest_ensure_response( $this->normalize_output( $cached ) );
			}

			return rest_ensure_response( $this->unavailable_output( $result ) );
		}

		return rest_ensure_response( $this->normalize_output( $result ) );
	}

	public function handle_credits_status( \WP_REST_Request $request ) {
		unset( $request );
		$result = Credits_Service::instance()->get_status( 0 );
		if ( is_wp_error( $result ) ) {
			return rest_ensure_response( $this->unavailable_output() );
		}

		return rest_ensure_response( $this->normalize_output( $result ) );
	}

	private function normalize_output( array $result ): array {
		$has_balance = array_key_exists( 'balance', $result ) && null !== $result['balance'] && is_numeric( $result['balance'] );
		$has_plan    = array_key_exists( 'hasPlan', $result ) ? (bool) $result['hasPlan'] : null;

		$result['balance']    = $has_balance ? (float) $result['balance'] : null;
		$result['hasPlan']    = $has_plan;
		$result['provenance'] = in_array( $result['provenance'] ?? '', [ 'fresh', 'stale' ], true )
			? (string) $result['provenance']
			: 'unavailable';
		$result['fetchedAt']  = isset( $result['fetchedAt'] ) ? (int) $result['fetchedAt'] : null;
		$result['ttlSeconds'] = Credits_Service::TTL_SECONDS;

		return $result;
	}

	private function unavailable_output( ?\WP_Error $error = null ): array {
		$output = [
			'balance'                   => null,
			'topupBalance'              => null,
			'subscriptionBalance'       => null,
			'billingSubscriptionStatus' => '',
			'activePlan'                => [],
			'hasPlan'                   => null,
			'provenance'                => 'unavailable',
			'available'                 => false,
			'fresh'                     => false,
			'stale'                     => false,
			'cached'                    => false,
			'fetchedAt'                 => null,
			'expiresAt'                 => null,
			'ttlSeconds'                => Credits_Service::TTL_SECONDS,
		];

		if ( null !== $error ) {
			$output['refreshError'] = true;
			$output['errorCode']    = sanitize_key( (string) $error->get_error_code() );
		}

		return $output;
	}
}
