<?php

namespace Modules\Event\Http\Controllers\Api;

use App\Http\Controllers\Api\ApiController;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\Rule;
use Modules\Event\Entities\Event;
use Symfony\Component\HttpFoundation\Response;

class SubmitParticipantEventController extends ApiController
{
    /**
     * Handle the incoming request.
     */
    public function __invoke(Request $request, Event $event)
    {
        $validator = Validator::make($request->all(), [
            'name' => ['required', 'string', 'max:100'],
            'designation' => ['required', 'string', 'max:100'],
            'company' => ['required', 'string', 'max:100'],
            'email' => ['required', 'email', Rule::unique('participants')->where('event_id', $event->id)],
            'contact_no' => ['required', 'string', 'max:20'],
        ], $this->addValidationErrorCode(), ['contact_no' => 'phone no']);

        if ($validator->fails()) {
            return $this->handleValidationResponse($validator->errors()->toArray());
        }

        DB::beginTransaction();

        try {
            $participant = $event->participants()->create($validator->validated());

            DB::commit();

            return $this->json([
                // 'type' => 'participant',
                'hash' => $participant->hash_id,
            ], Response::HTTP_CREATED);
        } catch (\Exception $e) {
            DB::rollBack();

            // report($e);

            return $this->jsonError(Response::HTTP_UNPROCESSABLE_ENTITY, $e->getMessage());
        }
    }
}
