<?php

namespace App\Http\Controllers\Api\Platform;

use App\Exceptions\DisputeAlreadyUnderwayException;
use App\Http\Controllers\Controller;
use App\Models\Dispute;
use App\RequestRules\Api\DisputeRequestRules;
use Illuminate\Contracts\Foundation\Application;
use Illuminate\Contracts\Routing\ResponseFactory;
use Illuminate\Http\Request;
use Illuminate\Http\Response;

class DisputeController extends Controller
{
   /**
    * Create new dispute
    *
    * @param Request $request
    * @return Response|Application|ResponseFactory
    */
   public function create(Request $request): Response|Application|ResponseFactory
   {
      $request->validate(DisputeRequestRules::creationRules());

      try {
         /** @var ?Dispute $dispute */
         $dispute = Dispute::addNewDispute($request->all());

         if ($dispute !== null) {
            return api_response(100, "Okay", $dispute->serializeForChannel());
         }
      } catch (\Exception $exception) {
         if($exception instanceof DisputeAlreadyUnderwayException) {
            return api_response(101, __('errors.ongoing_dispute_exists'));
         }
      }

      return api_response(101, __('errors.unknown_error'));
   }

   /**
    * Get dispute by uuid
    *
    * @param string $uuid
    * @return Response|Application|ResponseFactory
    */
   public function getDispute(string $uuid): Response|Application|ResponseFactory
   {
      /** @var ?Dispute $dispute */
      $dispute = Dispute::findByUuid($uuid);

      if ($dispute !== null) {
         return api_response(100, "Okay", $dispute->serializeForChannel());
      }

      return api_response(101);
   }

   /**
    * Dispute history
    *
    * @return Response|Application|ResponseFactory
    */
   public function history(): Response|Application|ResponseFactory
   {
      $history = Dispute::history();

      return api_response(100, "Okay", $history);
   }
}
