<?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 FeedAnalyticsController extends Controller
{
    public function store(Request $request): JsonResponse
    {
        $payload = $request->validate([
            'event_type' => ['required', 'string', 'in:feed_impression,feed_click'],
            'artwork_id' => ['required', 'integer', 'exists:artworks,id'],
            'position' => ['nullable', 'integer', 'min:1', 'max:500'],
            'algo_version' => ['required', 'string', 'max:64'],
            'source' => ['required', 'string', 'in:personalized,cold_start,fallback'],
            'dwell_seconds' => ['nullable', 'integer', 'min:0', 'max:86400'],
            'occurred_at' => ['nullable', 'date'],
        ]);

        $occurredAt = isset($payload['occurred_at']) ? now()->parse((string) $payload['occurred_at']) : now();

        DB::table('feed_events')->insert([
            'event_date' => $occurredAt->toDateString(),
            'event_type' => (string) $payload['event_type'],
            'user_id' => (int) $request->user()->id,
            'artwork_id' => (int) $payload['artwork_id'],
            'position' => isset($payload['position']) ? (int) $payload['position'] : null,
            'algo_version' => (string) $payload['algo_version'],
            'source' => (string) $payload['source'],
            'dwell_seconds' => isset($payload['dwell_seconds']) ? (int) $payload['dwell_seconds'] : null,
            'occurred_at' => $occurredAt,
            'created_at' => now(),
            'updated_at' => now(),
        ]);

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