<?php

namespace App\Http\Controllers\Api\Admin;

use App\Domains\Billing\Models\Plan;
use App\Domains\Tenancy\Models\Tenant;
use App\Http\Controllers\Controller;
use App\Support\PlatformSettings;
use Illuminate\Http\JsonResponse;

class AdminDashboardController extends Controller
{
    private const SETTINGS_SCHEMA = [
        'openai' => [
            ['key' => 'AI_PROVIDER', 'label' => 'AI Provider', 'sensitive' => false, 'type' => 'text'],
            ['key' => 'AI_OPENAI_API_KEY', 'label' => 'OpenAI API Key', 'sensitive' => true, 'type' => 'password'],
            ['key' => 'AI_OPENAI_MODEL', 'label' => 'OpenAI Model', 'sensitive' => false, 'type' => 'text'],
            ['key' => 'AI_OPENAI_BASE_URL', 'label' => 'OpenAI Base URL', 'sensitive' => false, 'type' => 'url'],
            ['key' => 'AI_OPENAI_TIMEOUT', 'label' => 'AI Timeout (seconds)', 'sensitive' => false, 'type' => 'number'],
        ],
        'whatsapp' => [
            ['key' => 'WHATSAPP_APP_ID', 'label' => 'WhatsApp App ID', 'sensitive' => false, 'type' => 'text'],
            ['key' => 'WHATSAPP_APP_SECRET', 'label' => 'WhatsApp App Secret', 'sensitive' => true, 'type' => 'password'],
            ['key' => 'WHATSAPP_VERIFY_TOKEN', 'label' => 'WhatsApp Verify Token', 'sensitive' => true, 'type' => 'password'],
            ['key' => 'WHATSAPP_WEBHOOK_SECRET', 'label' => 'WhatsApp Webhook Secret', 'sensitive' => true, 'type' => 'password'],
        ],
        'instagram' => [
            ['key' => 'INSTAGRAM_APP_ID', 'label' => 'Instagram App ID', 'sensitive' => false, 'type' => 'text'],
            ['key' => 'INSTAGRAM_APP_SECRET', 'label' => 'Instagram App Secret', 'sensitive' => true, 'type' => 'password'],
            ['key' => 'INSTAGRAM_VERIFY_TOKEN', 'label' => 'Instagram Verify Token', 'sensitive' => true, 'type' => 'password'],
            ['key' => 'INSTAGRAM_WEBHOOK_SECRET', 'label' => 'Instagram Webhook Secret', 'sensitive' => true, 'type' => 'password'],
        ],
        'whish' => [
            ['key' => 'PAYMENT_DEFAULT_PROVIDER', 'label' => 'Default Payment Provider', 'sensitive' => false, 'type' => 'text'],
            ['key' => 'WHISH_API_BASE_URL', 'label' => 'Whish API Base URL', 'sensitive' => false, 'type' => 'url'],
            ['key' => 'WHISH_MERCHANT_ID', 'label' => 'Whish Merchant ID', 'sensitive' => false, 'type' => 'text'],
            ['key' => 'WHISH_MERCHANT_SECRET', 'label' => 'Whish Merchant Secret', 'sensitive' => true, 'type' => 'password'],
            ['key' => 'WHISH_WEBHOOK_SECRET', 'label' => 'Whish Webhook Secret', 'sensitive' => true, 'type' => 'password'],
            ['key' => 'WHISH_CHECKOUT_BASE_URL', 'label' => 'Whish Checkout Base URL', 'sensitive' => false, 'type' => 'url'],
        ],
    ];

    public function __invoke(): JsonResponse
    {
        return response()->json([
            'data' => [
                'tenants' => Tenant::query()->count(),
                'trialTenants' => Tenant::query()->where('status', 'trial')->count(),
                'activeTenants' => Tenant::query()->where('status', 'active')->count(),
                'plans' => Plan::query()->count(),
                'settings' => $this->settings(),
            ],
        ]);
    }

    /**
     * @return array<string, array<int, array<string, mixed>>>
     */
    private function settings(): array
    {
        return collect(self::SETTINGS_SCHEMA)->mapWithKeys(function (array $fields, string $section): array {
            $rows = collect($fields)->map(function (array $field): array {
                $key = $field['key'];
                $fallback = $this->fallbackValue($key);
                $stored = PlatformSettings::get($key);
                $configured = PlatformSettings::has($key) || ($fallback !== null && $fallback !== '');

                return [
                    'key' => $key,
                    'label' => $field['label'],
                    'type' => $field['type'],
                    'sensitive' => $field['sensitive'],
                    'configured' => $configured,
                    'value' => $field['sensitive'] ? '' : (string) ($stored ?? $fallback ?? ''),
                ];
            })->values()->all();

            return [$section => $rows];
        })->all();
    }

    private function fallbackValue(string $key): ?string
    {
        return match ($key) {
            'AI_PROVIDER' => (string) config('ai.default_provider'),
            'AI_OPENAI_MODEL' => (string) config('ai.providers.openai.model'),
            'AI_OPENAI_BASE_URL' => (string) config('ai.providers.openai.base_url'),
            'AI_OPENAI_TIMEOUT' => (string) config('ai.providers.openai.timeout'),
            'WHATSAPP_APP_ID' => (string) config('channels.whatsapp.app_id'),
            'WHATSAPP_APP_SECRET' => (string) config('channels.whatsapp.app_secret'),
            'WHATSAPP_VERIFY_TOKEN' => (string) config('channels.whatsapp.verify_token'),
            'WHATSAPP_WEBHOOK_SECRET' => (string) config('channels.whatsapp.webhook_secret'),
            'INSTAGRAM_APP_ID' => (string) config('channels.instagram.app_id'),
            'INSTAGRAM_APP_SECRET' => (string) config('channels.instagram.app_secret'),
            'INSTAGRAM_VERIFY_TOKEN' => (string) config('channels.instagram.verify_token'),
            'INSTAGRAM_WEBHOOK_SECRET' => (string) config('channels.instagram.webhook_secret'),
            'PAYMENT_DEFAULT_PROVIDER' => (string) config('payments.default_provider'),
            'WHISH_API_BASE_URL' => (string) config('payments.providers.whish.base_url'),
            'WHISH_MERCHANT_ID' => (string) config('payments.providers.whish.merchant_id'),
            'WHISH_MERCHANT_SECRET' => (string) config('payments.providers.whish.merchant_secret'),
            'WHISH_WEBHOOK_SECRET' => (string) config('payments.providers.whish.webhook_secret'),
            'WHISH_CHECKOUT_BASE_URL' => (string) config('payments.providers.whish.checkout_base_url'),
            default => null,
        };
    }
}
