<?php

namespace Fotogenic_AI;

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

final class Plugin_Cache_Refresher {
    private static ?Plugin_Cache_Refresher $instance = null;

    private function __construct() {}

    public static function instance(): Plugin_Cache_Refresher {
        if ( null === self::$instance ) {
            self::$instance = new self();
        }

        return self::$instance;
    }

    public function refresh(): array {
        $settings = Settings::instance();
        $options  = $settings->get_options();
        $env      = (string) ( $options['api_environment'] ?? 'production' );
        $auth     = Auth_Session::instance();
        $identity = $auth->get_cache_identity();

        $config_service = new Service_Configuration();
        $config_service->clear_cache_for_identity( $identity );
        Config_Provider::clear_memory();

        Price_Service::instance()->clear_cache();

        $library_service = new Service_Library();
        $library_service->invalidate_library_cache();

        Studio_Cache_Store::flush_all_caches();
        Bulk_Cache_Version::bump();

        $credits_service = Credits_Service::instance();
        $credits_service->clear_user_cache( $identity, $env );

        $credits = null;

        if ( $auth->is_connected() ) {
            $credits_result = $credits_service->refresh( 0 );

            if ( is_wp_error( $credits_result ) ) {
                $credits = [
                    'available'   => false,
                    'errorCode'   => (string) $credits_result->get_error_code(),
                    'errorStatus' => (int) ( $credits_result->get_error_data()['status'] ?? 0 ),
                ];
            } elseif ( is_array( $credits_result ) ) {
                $credits = $credits_result;
            }
        }

        return [
            'auth'    => $auth->get_public_status(),
            'credits' => $credits,
        ];
    }
}
