<?php

namespace App\Http\Controllers;

use App\Models\AppSetting;
use App\Support\WhatsAppConfig;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Schema;
use Illuminate\Support\Facades\Crypt;
use Throwable;

/**
 * Admin-only CRUD for WhatsApp Business API credentials stored in app_settings (encrypted secrets).
 */
class WhatsAppSettingsController extends Controller
{
    public function show()
    {
        if (! Schema::hasTable('app_settings')) {
            return response()->json([
                'message' => 'Falta ejecutar migraciones (tabla app_settings).',
            ], 503);
        }

        return response()->json($this->payload());
    }

    public function update(Request $request)
    {
        if (! Schema::hasTable('app_settings')) {
            return response()->json([
                'message' => 'Falta ejecutar migraciones (tabla app_settings).',
            ], 503);
        }

        $request->validate([
            'phone_number_id' => 'nullable|string|max:80',
            'verify_token' => 'nullable|string|max:120',
            'api_version' => 'nullable|string|max:20',
            'access_token' => 'nullable|string|max:4096',
            'app_secret' => 'nullable|string|max:256',
        ]);

        if ($request->filled('phone_number_id')) {
            AppSetting::setValue(WhatsAppConfig::keyPhoneNumberId(), trim((string) $request->input('phone_number_id')));
        }

        if ($request->filled('verify_token')) {
            AppSetting::setValue(WhatsAppConfig::keyVerifyToken(), trim((string) $request->input('verify_token')));
        }

        if ($request->filled('api_version')) {
            AppSetting::setValue(WhatsAppConfig::keyApiVersion(), trim((string) $request->input('api_version')));
        }

        $tokenIn = $request->filled('access_token') ? trim((string) $request->input('access_token')) : '';
        if ($tokenIn !== '') {
            try {
                AppSetting::setValue(WhatsAppConfig::keyTokenEnc(), Crypt::encryptString($tokenIn));
            } catch (Throwable $e) {
                return response()->json([
                    'message' => 'No se pudo guardar el token de acceso.',
                    'errors' => ['access_token' => [$e->getMessage()]],
                ], 422);
            }
        }

        $secretIn = $request->filled('app_secret') ? trim((string) $request->input('app_secret')) : '';
        if ($secretIn !== '') {
            try {
                AppSetting::setValue(WhatsAppConfig::keyAppSecretEnc(), Crypt::encryptString($secretIn));
            } catch (Throwable $e) {
                return response()->json([
                    'message' => 'No se pudo guardar el App Secret.',
                    'errors' => ['app_secret' => [$e->getMessage()]],
                ], 422);
            }
        }

        return response()->json(array_merge([
            'message' => 'Ajustes de WhatsApp guardados.',
        ], $this->payload()));
    }

    private function payload(): array
    {
        $base = rtrim((string) config('app.url'), '/');

        return [
            'webhook_url' => $base . '/api/webhooks/whatsapp',
            'api_version' => $this->displayApiVersion(),
            'phone_number_id' => WhatsAppConfig::hasStoredPhoneNumberId()
                ? (string) AppSetting::getValue(WhatsAppConfig::keyPhoneNumberId())
                : '',
            'phone_number_id_source' => WhatsAppConfig::hasStoredPhoneNumberId() ? 'database' : (config('services.whatsapp.phone_number_id') ? 'env' : 'none'),
            'verify_token_set' => $this->isVerifyTokenSet(),
            'access_token_set' => $this->isAccessTokenSet(),
            'app_secret_set' => $this->isAppSecretSet(),
            'is_configured' => ! empty(WhatsAppConfig::accessToken()) && ! empty(WhatsAppConfig::phoneNumberId()),
        ];
    }

    private function displayApiVersion(): string
    {
        if (WhatsAppConfig::hasStoredApiVersion()) {
            return (string) AppSetting::getValue(WhatsAppConfig::keyApiVersion());
        }

        return (string) (config('services.whatsapp.api_version') ?? 'v21.0');
    }

    private function isVerifyTokenSet(): bool
    {
        return WhatsAppConfig::hasStoredVerifyToken() || ! empty(config('services.whatsapp.verify_token'));
    }

    private function isAccessTokenSet(): bool
    {
        return WhatsAppConfig::hasStoredAccessToken() || ! empty(config('services.whatsapp.token'));
    }

    private function isAppSecretSet(): bool
    {
        return WhatsAppConfig::hasStoredAppSecret() || ! empty(config('services.whatsapp.app_secret'));
    }
}
