<?php

namespace App\Http\Controllers\Api\Billing;

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

class UpdatePaymentProviderController extends Controller
{
    public function __invoke(UpdatePaymentProviderRequest $request, string $provider): JsonResponse
    {
        $record = PaymentProvider::query()
            ->where('tenant_id', $request->user()->tenant_id)
            ->where('provider_key', $provider)
            ->firstOrFail();

        $data = $request->validated();
        $credentials = is_array($record->credentials_json) ? $record->credentials_json : [];

        $record->update([
            'is_enabled' => $data['is_enabled'] ?? $record->is_enabled,
            'is_live_mode' => $data['is_live_mode'] ?? $record->is_live_mode,
            'credentials_json' => [
                'merchant_id' => $data['merchant_id'] ?? ($credentials['merchant_id'] ?? null),
                'merchant_secret' => ! empty($data['merchant_secret'])
                    ? Crypt::encryptString($data['merchant_secret'])
                    : ($credentials['merchant_secret'] ?? null),
                'allow_cod' => array_key_exists('allow_cod', $data)
                    ? (bool) $data['allow_cod']
                    : (bool) ($credentials['allow_cod'] ?? true),
                'allow_manual_whish' => array_key_exists('allow_manual_whish', $data)
                    ? (bool) $data['allow_manual_whish']
                    : (bool) ($credentials['allow_manual_whish'] ?? false),
                'manual_whish_number' => array_key_exists('manual_whish_number', $data)
                    ? ($data['manual_whish_number'] ?: null)
                    : ($credentials['manual_whish_number'] ?? null),
            ],
            'webhook_secret' => ! empty($data['webhook_secret'])
                ? Crypt::encryptString($data['webhook_secret'])
                : $record->webhook_secret,
            'checkout_base_url' => $data['checkout_base_url'] ?? $record->checkout_base_url,
        ]);

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