<?php

/**
 * 文件功能：后台成就记录查询控制器。
 *
 * 提供固定成就目录的解锁统计与用户成就记录只读查询。
 */

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\UserAchievement;
use App\Support\AchievementCatalog;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\View\View;

/**
 * 类功能：展示后台成就总览、解锁记录与按成就分组统计。
 */
class AchievementController extends Controller
{
    /**
     * 展示成就记录总览。
     */
    public function index(Request $request): View
    {
        $definitions = AchievementCatalog::definitions();
        $query = UserAchievement::query()
            ->with('user:id,username')
            ->whereNotNull('achieved_at')
            ->latest('achieved_at');

        if ($request->filled('username')) {
            $query->whereHas('user', function ($userQuery) use ($request): void {
                $userQuery->where('username', 'like', '%'.$request->string('username')->toString().'%');
            });
        }

        if ($request->filled('achievement_key')) {
            $query->where('achievement_key', $request->string('achievement_key')->toString());
        }

        $records = $query->paginate(30)->withQueryString();
        $summary = [
            'total_definitions' => count($definitions),
            'unlocked_records' => UserAchievement::query()->whereNotNull('achieved_at')->count(),
            'unlocked_users' => UserAchievement::query()->whereNotNull('achieved_at')->distinct('user_id')->count('user_id'),
        ];
        $topAchievements = UserAchievement::query()
            ->whereNotNull('achieved_at')
            ->select('achievement_key', DB::raw('count(*) as unlocked_count'))
            ->groupBy('achievement_key')
            ->orderByDesc('unlocked_count')
            ->limit(10)
            ->get();

        return view('admin.achievements.index', compact('definitions', 'records', 'summary', 'topAchievements'));
    }
}
