<?php

declare(strict_types=1);

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Services\Worlds\WorldAnalyticsService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Validation\Rule;

final class WorldAnalyticsEventController extends Controller
{
    public function __construct(
        private readonly WorldAnalyticsService $analytics,
    ) {
    }

    public function store(Request $request): JsonResponse
    {
        $payload = $request->validate([
            'world_id' => ['required', 'integer', 'exists:worlds,id'],
            'event_type' => ['required', 'string', Rule::in($this->analytics->allowedEventTypes())],
            'section_key' => ['sometimes', 'nullable', 'string', 'max:80'],
            'cta_key' => ['sometimes', 'nullable', 'string', 'max:80'],
            'entity_type' => ['sometimes', 'nullable', 'string', 'max:40'],
            'entity_id' => ['sometimes', 'nullable', 'integer', 'min:1'],
            'entity_title' => ['sometimes', 'nullable', 'string', 'max:180'],
            'challenge_id' => ['sometimes', 'nullable', 'integer', 'min:1'],
            'source_surface' => ['sometimes', 'nullable', 'string', Rule::in($this->analytics->allowedSourceSurfaces())],
            'source_detail' => ['sometimes', 'nullable', 'string', 'max:80'],
            'visitor_token' => ['sometimes', 'nullable', 'string', 'max:100'],
            'meta' => ['sometimes', 'array'],
        ]);

        $this->analytics->recordEvent($request, $payload);

        return response()->json([
            'ok' => true,
        ], 202);
    }
}