<?php

/**
 * 文件功能：神秘占卜前台控制器
 *
 * 提供用户每日占卜功能：
 * - 查询今日占卜状态（已占卜/未占卜/剩余次数）
 * - 执行占卜（免费或付费）
 * - 查询占卜历史记录
 *
 * @author  ChatRoom Laravel
 *
 * @version 1.0.0
 */

namespace App\Http\Controllers;

use App\Enums\CurrencySource;
use App\Models\FortuneLog;
use App\Models\GameConfig;
use App\Services\UserCurrencyService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class FortuneTellingController extends Controller
{
    public function __construct(
        private readonly UserCurrencyService $currency,
    ) {}

    /**
     * 查询今日占卜状态（用于面板初始化和刷新）。
     */
    public function todayStatus(Request $request): JsonResponse
    {
        if (! GameConfig::isEnabled('fortune_telling')) {
            return response()->json(['enabled' => false]);
        }

        $user = $request->user();
        $config = GameConfig::forGame('fortune_telling')?->params ?? [];

        $freeCount = (int) ($config['free_count_per_day'] ?? 1);
        $extraCost = (int) ($config['extra_cost'] ?? 500);

        $todayCount = FortuneLog::todayCount($user->id);
        $todayLatest = FortuneLog::todayLatest($user->id);
        $freeUsed = FortuneLog::query()
            ->where('user_id', $user->id)
            ->where('fortune_date', today())
            ->where('is_free', true)
            ->count();
        $hasFreeLeft = $freeUsed < $freeCount;

        return response()->json([
            'enabled' => true,
            'today_count' => $todayCount,
            'free_count' => $freeCount,
            'free_used' => $freeUsed,
            'has_free_left' => $hasFreeLeft,
            'extra_cost' => $extraCost,
            'latest' => $todayLatest ? [
                'grade' => $todayLatest->grade,
                'grade_label' => $todayLatest->gradeLabel(),
                'grade_color' => $todayLatest->gradeColor(),
                'text' => $todayLatest->text,
                'buff_desc' => $todayLatest->buff_desc,
                'created_at' => $todayLatest->created_at->format('H:i'),
            ] : null,
        ]);
    }

    /**
     * 执行一次占卜。
     *
     * 免费次数用完后每次消耗 extra_cost 金币。
     */
    public function tell(Request $request): JsonResponse
    {
        if (! GameConfig::isEnabled('fortune_telling')) {
            return response()->json(['ok' => false, 'message' => '神秘占卜当前未开启。']);
        }

        $user = $request->user();
        $config = GameConfig::forGame('fortune_telling')?->params ?? [];

        $freeCount = (int) ($config['free_count_per_day'] ?? 1);
        $extraCost = (int) ($config['extra_cost'] ?? 500);

        // 判断今日免费次数是否已用完
        $freeUsed = FortuneLog::query()
            ->where('user_id', $user->id)
            ->where('fortune_date', today())
            ->where('is_free', true)
            ->count();

        $isFree = $freeUsed < $freeCount;
        $cost = $isFree ? 0 : $extraCost;

        // 检查余额
        if (! $isFree && ($user->jjb ?? 0) < $cost) {
            return response()->json(['ok' => false, 'message' => "金币不足，额外占卜需要 {$cost} 金币。"]);
        }

        // 扣费
        if (! $isFree && $cost > 0) {
            $this->currency->change(
                $user,
                'gold',
                -$cost,
                CurrencySource::FORTUNE_COST,
                '神秘占卜额外次数消耗',
            );
        }

        // 抽签
        $grade = FortuneLog::rollGrade($config);
        $fortune = FortuneLog::rollFortune($grade);

        // 记录
        $log = FortuneLog::create([
            'user_id' => $user->id,
            'grade' => $grade,
            'text' => $fortune['text'],
            'buff_desc' => $fortune['buff_desc'] ?? null,
            'is_free' => $isFree,
            'cost' => $cost,
            'fortune_date' => today(),
        ]);

        return response()->json([
            'ok' => true,
            'grade' => $log->grade,
            'grade_label' => $log->gradeLabel(),
            'grade_color' => $log->gradeColor(),
            'text' => $log->text,
            'buff_desc' => $log->buff_desc,
            'is_free' => $isFree,
            'cost' => $cost,
        ]);
    }

    /**
     * 查询近20条个人占卜历史记录。
     */
    public function history(Request $request): JsonResponse
    {
        $logs = FortuneLog::query()
            ->where('user_id', $request->user()->id)
            ->orderByDesc('id')
            ->limit(20)
            ->get(['grade', 'text', 'buff_desc', 'is_free', 'cost', 'fortune_date', 'created_at'])
            ->map(fn ($log) => [
                'grade' => $log->grade,
                'grade_label' => $log->gradeLabel(),
                'grade_color' => $log->gradeColor(),
                'text' => $log->text,
                'buff_desc' => $log->buff_desc,
                'cost' => $log->cost,
                'date' => $log->fortune_date->format('m-d'),
                'time' => $log->created_at->format('H:i'),
            ]);

        return response()->json(['history' => $logs]);
    }
}
