<?php

declare(strict_types=1);

namespace App\Http\Controllers\Api;

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

final class SimilarArtworkAnalyticsController extends Controller
{
    public function store(Request $request): JsonResponse
    {
        $payload = $request->validate([
            'event_type' => ['required', 'string', 'in:impression,click'],
            'algo_version' => ['required', 'string', 'max:64'],
            'source_artwork_id' => ['required', 'integer', 'exists:artworks,id'],
            'similar_artwork_id' => ['nullable', 'integer', 'exists:artworks,id'],
            'position' => ['nullable', 'integer', 'min:1', 'max:100'],
            'items_count' => ['nullable', 'integer', 'min:0', 'max:100'],
        ]);

        DB::table('similar_artwork_events')->insert([
            'event_date' => now()->toDateString(),
            'event_type' => (string) $payload['event_type'],
            'algo_version' => (string) $payload['algo_version'],
            'source_artwork_id' => (int) $payload['source_artwork_id'],
            'similar_artwork_id' => isset($payload['similar_artwork_id']) ? (int) $payload['similar_artwork_id'] : null,
            'position' => isset($payload['position']) ? (int) $payload['position'] : null,
            'items_count' => isset($payload['items_count']) ? (int) $payload['items_count'] : null,
            'occurred_at' => now(),
            'created_at' => now(),
            'updated_at' => now(),
        ]);

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