<?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 SubmitFeedbackEventController extends ApiController
{
    /**
     * Handle the incoming request.
     */
    public function __invoke(Request $request, Event $event)
    {
        $validator = Validator::make($request->all(), [
            'name' => ['required', 'string', 'max:100'],
            'message' => ['required', 'max:300'],
            'organization' => ['nullable', 'string', 'max:100'],
            'session' => ['required', 'string',
                // Rule::in(['']),
            ],
            'is_anonymous' => ['sometimes', 'boolean'],
        ], $this->addValidationErrorCode() , ['organization' => 'organisation' , 'session' => 'events/session' , 'message' => 'feedback'] );

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

        DB::beginTransaction();

        try {
            $feedback = $event->feedbacks()->create($validator->validated());

            DB::commit();

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

            // report($e);

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