<?php

namespace App\Http\Controllers\Api\V1;

use App\Http\Controllers\Controller;
use App\Models\PricingPlan;
use App\Models\Subscription;
use App\Models\User;
use App\Models\UserApiKey;
use App\Models\UserKeyword;
use App\Models\WebhookEvent;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class AdminAnalyticsController extends Controller
{
    private function authorizeAdmin(Request $request): ?JsonResponse
    {
        $token = (string) config('dewemoji.admin.token', '');
        $provided = trim((string) $request->header('X-Admin-Token', ''));
        if ($token === '' || $provided === '' || ! hash_equals($token, $provided)) {
            return response()->json(['ok' => false, 'error' => 'unauthorized'], 401);
        }

        return null;
    }

    public function overview(Request $request): JsonResponse
    {
        if ($res = $this->authorizeAdmin($request)) {
            return $res;
        }

        $totalUsers = User::count();
        $personalUsers = User::where('tier', 'personal')->count();
        $apiKeys = UserApiKey::count();
        $keywords = UserKeyword::count();
        $subscriptions = Subscription::count();
        $activeSubscriptions = Subscription::where('status', 'active')->count();
        $pricingPlans = PricingPlan::count();
        $webhooks = WebhookEvent::count();

        return response()->json([
            'ok' => true,
            'metrics' => [
                'users_total' => $totalUsers,
                'users_personal' => $personalUsers,
                'api_keys_total' => $apiKeys,
                'keywords_total' => $keywords,
                'subscriptions_total' => $subscriptions,
                'subscriptions_active' => $activeSubscriptions,
                'pricing_plans_total' => $pricingPlans,
                'webhook_events_total' => $webhooks,
            ],
        ]);
    }
}
