<?php

use Illuminate\Support\Facades\Log;

/**
 * Submit app licensed
 *
 * @param  string  $code
 */
function submitAppLicensed($code): array
{
    try {
        $response = getHttpClient(true)
            ->post(config('app.api_url').'/merchants/subscriptions/activate', [
                'code' => $code,
            ]);

        // Parse response once
        $data = $response->json();

        // Check if HTTP request was successful
        if (! $response->successful()) {
            $errorMessage = $data['error'] ?? $data['message'] ?? 'Échec de l\'activation de l\'abonnement';

            return [
                'success' => false,
                'error' => decodeUnicodeString($errorMessage),
            ];
        }

        // Check if API response indicates success
        if (! ($data['success'] ?? false)) {
            $errorMessage = $data['error'] ?? $data['message'] ?? 'Réponse API invalide';

            return [
                'success' => false,
                'error' => decodeUnicodeString($errorMessage),
            ];
        }

        // Success case - return all available data
        return [
            'success' => true,
            'message' => decodeUnicodeString($data['message'] ?? 'Activation réussie'),
            'subscription' => $data['subscription'] ?? null,
            'data' => $data, // Include full response for debugging
        ];

    } catch (\Exception $e) {
        ['message' => $friendlyMessage, 'status' => $status] = extractApiExceptionMessage($e, 'Échec de l\'activation de l\'abonnement');

        return [
            'success' => false,
            'error' => $friendlyMessage,
            'status' => $status,
        ];
    }
}


/**
 * Get subscriptions
 */
function getSubscriptions(): array
{
    try {
        // Check if we have a valid auth token before making the call
        if (! hasValidAuthToken()) {
            return [
                'success' => false,
                'has_active_subscription' => false,
                'message' => 'No authentication token available',
                'error' => 'Authentication required to check subscriptions',
            ];
        }

        $response = getHttpClient(true)->get(config('app.api_url').'/merchants/subscriptions/current');

        if (! $response->successful()) {
            return [
                'success' => false,
                'has_active_subscription' => false,
                'error' => 'Échec de la synchronisation avec le serveur',
                'status' => $response->status(),
            ];
        }

        $data = $response->json();

        // Ensure the response has the expected structure
        return [
            'success' => $data['success'] ?? true,
            'has_active_subscription' => $data['has_active_subscription'] ?? false,
            'subscription' => $data['subscription'] ?? null,
            'message' => $data['message'] ?? null,
            'error' => $data['error'] ?? null,
        ];
    } catch (\Exception $e) {
        ['message' => $friendlyMessage, 'status' => $status] = extractApiExceptionMessage($e, 'Échec de la synchronisation avec le serveur');

        return [
            'success' => false,
            'has_active_subscription' => false,
            'error' => $friendlyMessage,
            'status' => $status,
        ];
    }
}

/**
 * Get subscription history
 */
function getSubscriptionHistory(): array
{
    try {
        // Check if we have a valid auth token before making authenticated calls
        if (! hasValidAuthToken()) {
            return [
                'success' => false,
                'message' => 'No authentication token available',
                'data' => [],
            ];
        }

        $response = getHttpClient(true)->get(config('app.api_url').'/merchants/subscriptions/history');

        if (! $response->successful()) {
            $errorMessage = 'Échec de récupération de l\'historique des abonnements';

            try {
                $errorData = $response->json();
                if (isset($errorData['message'])) {
                    $errorMessage = decodeUnicodeString($errorData['message']);
                }
            } catch (\Exception $e) {
                // Keep default error message if JSON parsing fails
            }

            return [
                'success' => false,
                'error' => $errorMessage,
                'data' => [],
                'total' => 0,
            ];
        }

        $data = $response->json();

        return [
            'success' => $data['success'] ?? true,
            'data' => $data['data'] ?? [],
            'total' => $data['total'] ?? 0,
        ];
    } catch (\Illuminate\Http\Client\RequestException $e) {
        $errorMessage = 'Impossible de se connecter au serveur distant. Veuillez réessayer plus tard.';

        try {
            $response = $e->response;
            if ($response && $response->json()) {
                $errorData = $response->json();
                if (isset($errorData['message'])) {
                    $errorMessage = decodeUnicodeString($errorData['message']);
                }
            }
        } catch (\Exception $jsonException) {
            // Keep the original error message if JSON parsing fails
        }

        return [
            'success' => false,
            'error' => $errorMessage,
            'data' => [],
            'total' => 0,
        ];
    } catch (\Exception $e) {
        ['message' => $friendlyMessage] = extractApiExceptionMessage($e, 'Erreur inattendue');

        return [
            'success' => false,
            'error' => $friendlyMessage,
            'data' => [],
            'total' => 0,
        ];
    }
}

/**
 * Sync subscription history
 */
function syncSubscriptionHistory(): array
{
    $historyData = getSubscriptionHistory();

    if (! $historyData['success']) {
        return $historyData;
    }

    $synced = 0;
    $skipped = 0;
    $errors = 0;

    foreach ($historyData['data'] as $apiSubscription) {
        try {
            // Map API data to local model fields
            $localData = [
                'slug' => \Illuminate\Support\Str::orderedUuid(),
                'category' => $apiSubscription['category'],
                'code' => $apiSubscription['code_used'] ?? null,
                'start_date' => $apiSubscription['start_date'],
                'end_date' => $apiSubscription['end_date'],
                'duration_in_days' => \Carbon\Carbon::parse($apiSubscription['start_date'])->diffInDays(\Carbon\Carbon::parse($apiSubscription['end_date'])),
                'status' => $apiSubscription['status'] === 'active' ? \App\Models\Subscription::STATUS_ACTIVE : ($apiSubscription['status'] === 'expired' ? \App\Models\Subscription::STATUS_EXPIRED : \App\Models\Subscription::STATUS_INACTIVE),
                'api_id' => $apiSubscription['id'], // Store API ID for reference
                'activated_at' => $apiSubscription['activated_at'] ?? null,
            ];

            // Check if subscription already exists by API ID
            $existingSubscription = \App\Models\Subscription::where('api_id', $apiSubscription['id'])->first();

            if ($existingSubscription) {
                // Update existing subscription
                $existingSubscription->update($localData);
                $skipped++;
            } else {
                // Create new subscription
                \App\Models\Subscription::create($localData);
                $synced++;
            }
        } catch (\Exception $e) {
            $errors++;
            Log::error('Error syncing subscription: '.$e->getMessage(), [
                'api_subscription' => $apiSubscription,
            ]);
        }
    }

    return [
        'success' => true,
        'message' => 'Synchronisation terminée',
        'synced' => $synced,
        'skipped' => $skipped,
        'errors' => $errors,
        'total' => $historyData['total'],
    ];
}