<?php

namespace App\Http\Controllers\V3\Dashboard\Mission;

use App\Enums\MissionStates;
use App\Http\Controllers\Controller;
use App\Http\Requests\V3\Mission\TransportaionUnit\AllocateRequest;
use App\Http\Requests\V3\Mission\TransportaionUnit\DeallocateRequest;
use App\Http\Traits\ApiResponse;
use App\Models\Mission;
use App\Services\Cartables\Mission\TransportationUnitService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class TransportationUnitController extends Controller
{
    use ApiResponse;

    public function index(Request $request, TransportationUnitService $transportationUnitService): JsonResponse
    {
        return response()->json($transportationUnitService->dataTable($request));
    }

    public function allocate(AllocateRequest $request, Mission $mission): JsonResponse
    {
        DB::transaction(function () use ($request, $mission) {
            $mission->machines()->attach($request->machines);

            $mission->histories()->create([
                'user_id' => auth()->user()->id,
                'previous_state_id' => $mission->state_id,
                'previous_state_name' => $mission->state_name
            ]);

            $state = MissionStates::PENDING_CONFIRMATION->value;
            $mission->update([
                'state_id' => $state,
                'state_name' => MissionStates::name($state),
            ]);
        });

        return $this->successResponse();
    }

    public function deallocate(DeallocateRequest $request, Mission $mission): JsonResponse
    {
        DB::transaction(function () use ($request, $mission) {
            $mission->histories()->create([
                'user_id' => auth()->user()->id,
                'previous_state_id' => $mission->state_id,
                'previous_state_name' => $mission->state_name,
                'user_description' => $request->description
            ]);

            $state = MissionStates::REJECT_BY_TRANSPORTATION->value;

            $mission->update([
                'state_id' => $state,
                'state_name' => MissionStates::name($state),
                'description' => $request->description
            ]);
        });

        return $this->successResponse();
    }

    public function rahdaran(Mission $mission): JsonResponse
    {
        return $this->successResponse($mission->rahdaran()->get(['rahdaran.id', 'rahdaran.name', 'rahdaran.code']));
    }
}
