<?php

declare(strict_types=1);

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use Carbon\CarbonImmutable;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Symfony\Component\HttpFoundation\Response;

final class TagInteractionAnalyticsController extends Controller
{
    public function store(Request $request): JsonResponse
    {
        $payload = $request->validate([
            'event_type' => ['required', 'string', 'in:click'],
            'surface' => ['required', 'string', 'in:search_suggestion,recent_search,rescue_suggestion,related_chip,related_cluster,top_companion'],
            'tag_slug' => ['nullable', 'string', 'max:120'],
            'source_tag_slug' => ['nullable', 'string', 'max:120'],
            'query' => ['nullable', 'string', 'max:120'],
            'position' => ['nullable', 'integer', 'min:1', 'max:50'],
            'occurred_at' => ['nullable', 'date'],
            'meta' => ['nullable', 'array'],
        ]);

        if (($payload['surface'] ?? null) !== 'recent_search' && empty($payload['tag_slug'])) {
            return response()->json([
                'message' => 'The selected analytics surface requires a tag slug.',
                'errors' => ['tag_slug' => ['The tag slug field is required for this surface.']],
            ], Response::HTTP_UNPROCESSABLE_ENTITY);
        }

        $occurredAt = isset($payload['occurred_at'])
            ? CarbonImmutable::parse((string) $payload['occurred_at'])
            : CarbonImmutable::now();
        $sessionId = $request->hasSession() ? (string) $request->session()->getId() : '';
        $sessionKey = $sessionId !== '' ? hash('sha256', $sessionId) : null;

        DB::table('tag_interaction_events')->insert([
            'event_date' => $occurredAt->toDateString(),
            'event_type' => (string) $payload['event_type'],
            'surface' => (string) $payload['surface'],
            'user_id' => $request->user()?->id,
            'session_key' => $sessionKey,
            'tag_slug' => isset($payload['tag_slug']) ? (string) $payload['tag_slug'] : null,
            'source_tag_slug' => isset($payload['source_tag_slug']) ? (string) $payload['source_tag_slug'] : null,
            'query' => isset($payload['query']) ? trim((string) $payload['query']) : null,
            'position' => isset($payload['position']) ? (int) $payload['position'] : null,
            'meta' => $payload['meta'] ?? null,
            'occurred_at' => $occurredAt,
            'created_at' => now(),
            'updated_at' => now(),
        ]);

        return response()->json(['success' => true], Response::HTTP_OK);
    }
}
