<?php

namespace App\Http\Controllers\Api\Billing;

use App\Domains\Billing\Models\PaymentProvider;
use App\Http\Controllers\Controller;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\Crypt;

class PaymentProviderIndexController extends Controller
{
    public function __invoke(): JsonResponse
    {
        $providers = PaymentProvider::query()
            ->where('tenant_id', request()->user()->tenant_id)
            ->orderBy('display_name')
            ->get()
            ->map(function (PaymentProvider $provider): array {
                $credentials = is_array($provider->credentials_json) ? $provider->credentials_json : [];

                $merchantSecretEncrypted = (string) ($credentials['merchant_secret'] ?? '');
                $hasMerchantSecret = $merchantSecretEncrypted !== '';
                if ($hasMerchantSecret) {
                    try {
                        Crypt::decryptString($merchantSecretEncrypted);
                    } catch (\Throwable) {
                        // keep boolean true even if legacy/plaintext value exists
                    }
                }

                return [
                    'id' => $provider->id,
                    'providerKey' => $provider->provider_key,
                    'displayName' => $provider->display_name,
                    'isEnabled' => $provider->is_enabled,
                    'isLiveMode' => $provider->is_live_mode,
                    'checkoutBaseUrl' => $provider->checkout_base_url,
                    'merchantId' => $credentials['merchant_id'] ?? '',
                    'hasMerchantSecret' => $hasMerchantSecret,
                    'webhookSecretSet' => ! empty($provider->webhook_secret),
                    'allowCod' => (bool) ($credentials['allow_cod'] ?? true),
                    'allowManualWhish' => (bool) ($credentials['allow_manual_whish'] ?? false),
                    'manualWhishNumber' => $credentials['manual_whish_number'] ?? '',
                ];
            })
            ->values();

        return response()->json(['data' => $providers]);
    }
}
