<?php

namespace App\Http\Controllers\Api\Admin;

use App\Http\Controllers\Controller;
use App\Support\PlatformSettings;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class AdminPlatformSettingsUpdateController extends Controller
{
    /**
     * @var array<string>
     */
    private const ALLOWED_KEYS = [
        'AI_PROVIDER',
        'AI_OPENAI_API_KEY',
        'AI_OPENAI_MODEL',
        'AI_OPENAI_BASE_URL',
        'AI_OPENAI_TIMEOUT',
        'WHATSAPP_APP_ID',
        'WHATSAPP_APP_SECRET',
        'WHATSAPP_VERIFY_TOKEN',
        'WHATSAPP_WEBHOOK_SECRET',
        'INSTAGRAM_APP_ID',
        'INSTAGRAM_APP_SECRET',
        'INSTAGRAM_VERIFY_TOKEN',
        'INSTAGRAM_WEBHOOK_SECRET',
        'PAYMENT_DEFAULT_PROVIDER',
        'WHISH_API_BASE_URL',
        'WHISH_MERCHANT_ID',
        'WHISH_MERCHANT_SECRET',
        'WHISH_WEBHOOK_SECRET',
        'WHISH_CHECKOUT_BASE_URL',
    ];

    /**
     * @var array<string>
     */
    private const SENSITIVE_KEYS = [
        'AI_OPENAI_API_KEY',
        'WHATSAPP_APP_SECRET',
        'WHATSAPP_VERIFY_TOKEN',
        'WHATSAPP_WEBHOOK_SECRET',
        'INSTAGRAM_APP_SECRET',
        'INSTAGRAM_VERIFY_TOKEN',
        'INSTAGRAM_WEBHOOK_SECRET',
        'WHISH_MERCHANT_SECRET',
        'WHISH_WEBHOOK_SECRET',
    ];

    public function __invoke(Request $request): JsonResponse
    {
        $payload = (array) $request->validate([
            'settings' => ['required', 'array'],
            'settings.*' => ['nullable', 'string'],
        ])['settings'];

        foreach ($payload as $key => $value) {
            if (! in_array($key, self::ALLOWED_KEYS, true)) {
                continue;
            }

            $isSensitive = in_array($key, self::SENSITIVE_KEYS, true);
            $value = is_string($value) ? trim($value) : '';

            // For sensitive fields, empty means "keep current" to avoid accidental wipe.
            if ($isSensitive && $value === '') {
                continue;
            }

            PlatformSettings::set($key, $value, $isSensitive);
        }

        return response()->json([
            'message' => 'Platform API settings saved successfully.',
        ]);
    }
}
