<?php

namespace App\Services;

use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;

class AdminDashboardService
{
    /** @return array<string, mixed> */
    public function overview(): array
    {
        return Cache::remember('admin.dashboard.overview', now()->addSeconds(30), function (): array {
            $today = now()->startOfDay();
            $month = now()->startOfMonth();

            $metrics = [
                'total_users' => DB::table('users')->whereNull('deleted_at')->count(),
                'active_users' => DB::table('users')->whereNull('deleted_at')->where('status', 'active')->count(),
                'premium_users' => DB::table('users')->whereNull('deleted_at')->where('is_premium', true)->count(),
                'total_devices' => DB::table('devices')->whereNull('deleted_at')->count(),
                'online_devices' => DB::table('devices')->whereNull('deleted_at')->where('status', 'online')->count(),
                'lost_devices' => DB::table('devices')->whereNull('deleted_at')->where('status', 'lost')->count(),
                'theft_today' => DB::table('theft_events')->whereNull('deleted_at')->where('created_at', '>=', $today)->count(),
                'critical_alerts' => DB::table('theft_events')->whereNull('deleted_at')->where('risk_level', 'critical')->where('status', '!=', 'resolved')->count(),
                'revenue_today' => (float) DB::table('payments')->where('status', 'paid')->where('created_at', '>=', $today)->sum('amount'),
                'revenue_month' => (float) DB::table('payments')->where('status', 'paid')->where('created_at', '>=', $month)->sum('amount'),
                'notifications' => DB::table('notifications')->count(),
                'wallet_balance' => (float) DB::table('wallets')->where('status', 'active')->sum('balance'),
            ];

            $latestUsers = DB::table('users')
                ->whereNull('deleted_at')
                ->latest('created_at')
                ->limit(6)
                ->get(['uuid', 'full_name', 'email', 'status', 'is_premium', 'created_at']);

            $latestAlerts = DB::table('theft_events')
                ->join('devices', 'devices.id', '=', 'theft_events.device_id')
                ->whereNull('theft_events.deleted_at')
                ->latest('theft_events.created_at')
                ->limit(6)
                ->get([
                    'theft_events.incident_number', 'theft_events.event_title', 'theft_events.risk_level',
                    'theft_events.status', 'theft_events.created_at', 'devices.device_name',
                ]);

            $months = collect(range(5, 0))->map(fn (int $offset) => now()->subMonths($offset)->startOfMonth());
            $growth = $months->map(function ($date): int {
                return DB::table('users')->whereBetween('created_at', [$date, $date->copy()->endOfMonth()])->count();
            });

            return [
                'metrics' => $metrics,
                'latestUsers' => $latestUsers,
                'latestAlerts' => $latestAlerts,
                'chart' => [
                    'labels' => $months->map(fn ($date) => $date->format('M Y'))->all(),
                    'users' => $growth->all(),
                    'devices' => $months->map(fn ($date) => DB::table('devices')->whereBetween('created_at', [$date, $date->copy()->endOfMonth()])->count())->all(),
                ],
                'system' => [
                    'database' => DB::connection()->getPdo() ? 'Operational' : 'Unavailable',
                    'queue' => config('queue.default'),
                    'cache' => config('cache.default'),
                    'environment' => app()->environment(),
                ],
            ];
        });
    }
}
