<?php

/**
 * 文件功能：百家乐买单活动后台控制器
 *
 * 提供聊天室管理员在输入框上方快捷创建活动、
 * 查看当前活动并手动结束活动的 JSON 接口。
 */

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Http\Requests\StoreBaccaratLossCoverEventRequest;
use App\Models\BaccaratLossCoverEvent;
use App\Services\BaccaratLossCoverService;
use App\Services\PositionPermissionService;
use App\Support\PositionPermissionRegistry;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

/**
 * 类功能：处理聊天室顶部快捷入口创建与结束百家乐买单活动。
 */
class BaccaratLossCoverEventController extends Controller
{
    /**
     * 注入百家乐买单活动服务。
     */
    public function __construct(
        private readonly BaccaratLossCoverService $lossCoverService,
        private readonly PositionPermissionService $positionPermissionService,
    ) {}

    /**
     * 创建新的百家乐买单活动。
     */
    public function store(StoreBaccaratLossCoverEventRequest $request): JsonResponse
    {
        if (! $this->positionPermissionService->hasPermission($request->user(), PositionPermissionRegistry::ROOM_BACCARAT_LOSS_COVER)) {
            return response()->json([
                'ok' => false,
                'message' => '当前职务无权创建买单活动。',
            ], 403);
        }

        try {
            $event = $this->lossCoverService->createEvent($request->user(), $request->validated());
        } catch (\RuntimeException $exception) {
            return response()->json([
                'ok' => false,
                'message' => $exception->getMessage(),
            ], 422);
        }

        return response()->json([
            'ok' => true,
            'message' => "活动「{$event->title}」已创建成功。",
            'event_id' => $event->id,
        ]);
    }

    /**
     * 手动结束或取消一场百家乐买单活动。
     */
    public function close(Request $request, BaccaratLossCoverEvent $event): JsonResponse
    {
        if (! $this->positionPermissionService->hasPermission($request->user(), PositionPermissionRegistry::ROOM_BACCARAT_LOSS_COVER)) {
            return response()->json([
                'ok' => false,
                'message' => '当前职务无权结束买单活动。',
            ], 403);
        }

        $event = $this->lossCoverService->forceCloseEvent($event, $request->user());

        return response()->json([
            'ok' => true,
            'message' => '活动状态已更新。',
            'status' => $event->status,
        ]);
    }
}
