<?php

namespace App\Http\Controllers\Api;

use App\Events\VisitorScreenUpdated;
use App\Http\Controllers\Controller;
use App\Models\Conversation;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Http\Response;

class WidgetSessionEventController extends Controller
{
    public function options(): Response
    {
        return response('', 204, [
            'Access-Control-Allow-Origin' => '*',
            'Access-Control-Allow-Methods' => 'POST, OPTIONS',
            'Access-Control-Allow-Headers' => 'Content-Type, Accept',
        ]);
    }

    public function store(Request $request): JsonResponse
    {
        $validated = $request->validate([
            'widget_key' => 'required|string',
            'visitor_id' => 'required|string',
            'events' => 'required|array',
        ]);

        // Find the conversation for this visitor
        $conversation = Conversation::whereHas('organization', function ($query) use ($validated) {
            $query->where('widget_public_key', $validated['widget_key']);
        })->whereHas('contact', function ($query) use ($validated) {
            $query->where('provider_id', $validated['visitor_id']);
        })->first();

        if ($conversation) {
            // Broadcast the events directly to the dashboard
            VisitorScreenUpdated::dispatch((string) $conversation->id, $validated['events']);
        }

        return response()->json(['status' => 'ok'])->withHeaders([
            'Access-Control-Allow-Origin' => '*',
        ]);
    }
}
