<?php

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

use App\Enums\MissionStates;
use App\Http\Controllers\Controller;
use App\Http\Requests\V3\Mission\ControlUnit\FinishRequest;
use App\Http\Requests\V3\Mission\ControlUnit\StartRequest;
use App\Http\Traits\ApiResponse;
use App\Models\Mission;
use App\Services\Cartables\Mission\ControlUnitService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class ControlUnitController extends Controller
{
    use ApiResponse;
    public function index(Request $request, ControlUnitService $controlUnitService): JsonResponse
    {
        return response()->json($controlUnitService->datatable($request));
    }

    public function start(StartRequest $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,
            ]);

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

        return $this->successResponse();
    }

    public function finish(FinishRequest $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,
            ]);

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

        return $this->successResponse();
    }
}
