<?php

namespace App\Http\Controllers\Api\V1;

use App\Http\Controllers\Controller;
use App\Services\Meta\MetaConversionsApiService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;

class MetaConversionsApiController extends Controller
{
    public function track(Request $request, MetaConversionsApiService $metaCapi): JsonResponse
    {
        $validator = Validator::make($request->all(), [
            'event_name' => 'required|string|in:PageView,ViewContent,AddToCart,InitiateCheckout,Purchase',
            'event_id' => 'nullable|string|max:191',
            'event_time' => 'nullable|integer|min:1',
            'event_source_url' => 'nullable|string|max:2048',
            'fbp' => 'nullable|string|max:255',
            'fbc' => 'nullable|string|max:255',
            'custom_data' => 'nullable|array',
            'user_data' => 'nullable|array',
            'user_data.fbp' => 'nullable|string|max:255',
            'user_data.fbc' => 'nullable|string|max:255',
            'user_data.external_id' => 'nullable|string|max:255',
            'user_data.externalId' => 'nullable|string|max:255',
            'user_data.email' => 'nullable|string|max:255',
            'user_data.em' => 'nullable|string|max:255',
            'user_data.phone' => 'nullable|string|max:255',
            'user_data.ph' => 'nullable|string|max:255',
        ]);

        if ($validator->fails()) {
            return response()->json([
                'sent' => false,
                'errors' => $validator->errors(),
            ], 422);
        }

        $result = $metaCapi->track($request, $validator->validated());

        return response()->json($result, 202);
    }
}
