<?php

namespace App\Services;

use App\Models\Agent;
use App\Models\Backup;
use App\Models\TableSnapshot;
use App\Models\Website;
use App\Repositories\ActivityLogRepository;
use App\Repositories\BackupRepository;
use Illuminate\Support\Facades\DB;

class DashboardService
{
    public function __construct(
        protected ActivityLogRepository $activityLogs,
        protected BackupRepository $backups,
    ) {
    }

    public function cards(): array
    {
        $totalWebsites = Website::query()->count();
        $onlineWebsites = Website::query()->where('status', 'online')->count();
        $offlineWebsites = Website::query()->where('status', 'offline')->count();
        $totalDatabases = (int) Website::query()->sum('database_count');
        $latestBackups = Backup::query()->where('status', 'completed')->count();
        $failedOperations = Backup::query()->where('status', 'failed')->count()
            + Agent::query()->where('sync_status', 'stale')->count();
        $recentActivity = $this->activityLogs->recent(8)->count();
        $systemStatus = $totalWebsites > 0
            ? round(($onlineWebsites / $totalWebsites) * 100)
            : 0;

        return [
            ['label' => 'Total Websites', 'value' => $totalWebsites, 'meta' => 'Connected tenants'],
            ['label' => 'Online Websites', 'value' => $onlineWebsites, 'meta' => 'Healthy and reachable'],
            ['label' => 'Offline Websites', 'value' => $offlineWebsites, 'meta' => 'Need investigation'],
            ['label' => 'Total Databases', 'value' => $totalDatabases, 'meta' => 'Tracked via agents'],
            ['label' => 'Latest Backups', 'value' => $latestBackups, 'meta' => 'Completed snapshots'],
            ['label' => 'Failed Operations', 'value' => $failedOperations, 'meta' => 'Backups and agent syncs'],
            ['label' => 'Recent Activity', 'value' => $recentActivity, 'meta' => 'Logged actions'],
            ['label' => 'System Status', 'value' => "{$systemStatus}%", 'meta' => 'Availability score'],
        ];
    }

    public function recentActivity(int $limit = 10)
    {
        return $this->activityLogs->recent($limit);
    }

    public function recentBackups(int $limit = 6)
    {
        return $this->backups->recent($limit);
    }

    public function healthBreakdown(): array
    {
        return [
            'healthy' => Website::query()->where('health_status', 'healthy')->count(),
            'warning' => Website::query()->where('health_status', 'warning')->count(),
            'critical' => Website::query()->where('health_status', 'critical')->count(),
            'unknown' => Website::query()->where('health_status', 'unknown')->count(),
        ];
    }

    public function notificationCount(): int
    {
        return Website::query()->where('status', 'offline')->count()
            + Backup::query()->where('status', 'failed')->count();
    }

    public function headlineStats(): array
    {
        return [
            'average_latency' => (int) round((float) Agent::query()->avg('latency_ms')),
            'tracked_tables' => (int) TableSnapshot::query()->count(),
            'error_rate' => Website::query()->count() > 0
                ? round((Website::query()->whereIn('status', ['offline', 'degraded'])->count() / Website::query()->count()) * 100, 1)
                : 0,
            'active_sessions' => (int) DB::table('sessions')->whereNotNull('user_id')->count(),
        ];
    }
}
