<?php

namespace App\Services\Admin;

use App\Enums\CoachStatus;
use App\Enums\PaymentStatus;
use App\Enums\ReviewStatus;
use App\Enums\UserRole;
use App\Models\AuditLog;
use App\Models\Goal;
use App\Models\Payment;
use App\Models\Review;
use App\Models\User;

/**
 * نسخه به‌روزشده Phase 13 — نسخه Phase 10 را جایگزین کنید.
 * تغییر: افزوده شدن pendingReviewsCount() — دقیقاً همان چیزی که در
 * docs/architecture-addendum.md (Phase 2) به این فاز موکول شده بود.
 */
class DashboardStatsService
{
    public function coachesTotal(): int
    {
        return User::query()->where('role', UserRole::Coach)->count();
    }

    public function coachesApproved(): int
    {
        return User::query()
            ->where('role', UserRole::Coach)
            ->whereHas('coach', fn ($q) => $q->where('status', CoachStatus::Approved))
            ->count();
    }

    public function coachesPending(): int
    {
        return User::query()
            ->where('role', UserRole::Coach)
            ->whereHas('coach', fn ($q) => $q->where('status', CoachStatus::Pending))
            ->count();
    }

    public function athletesTotal(): int
    {
        return User::query()->where('role', UserRole::Athlete)->count();
    }

    public function activeGoalsCount(): int
    {
        return Goal::query()->active()->count();
    }

    public function pendingPaymentsCount(): int
    {
        return Payment::query()->where('status', PaymentStatus::PendingReview)->count();
    }

    /**
     * مجموع نظراتی که هنوز در گردش تأیید هستند (چه در انتظار مربی، چه در
     * انتظار Admin) — رفع باگ: قبلاً به ReviewStatus::Pending اشاره می‌کرد که
     * از Phase 15 (Workflow دو‌مرحله‌ای) دیگر وجود نداشت.
     */
    public function pendingReviewsCount(): int
    {
        return Review::query()
            ->whereIn('status', [ReviewStatus::PendingCoach, ReviewStatus::PendingAdmin])
            ->count();
    }

    public function recentAuditLogs(int $limit = 8)
    {
        return AuditLog::with('user')->latest('created_at')->limit($limit)->get();
    }

    public function summary(): array
    {
        return [
            'coaches_total' => $this->coachesTotal(),
            'coaches_approved' => $this->coachesApproved(),
            'coaches_pending' => $this->coachesPending(),
            'athletes_total' => $this->athletesTotal(),
            'active_goals' => $this->activeGoalsCount(),
            'pending_payments' => $this->pendingPaymentsCount(),
            'pending_reviews' => $this->pendingReviewsCount(),
            'recent_logs' => $this->recentAuditLogs(),
        ];
    }
}
