<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Http\Requests\Api\StoreUnitSubtypeRequest;
use App\Http\Requests\Api\UpdateUnitSubtypeRequest;
use App\Http\Resources\UnitSubtypeResource;
use App\Models\Unit;
use App\Models\UnitSubtype;
use App\Models\User;
use App\Services\UnitSubtypeService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Response;

class UnitSubtypeController extends Controller
{
    public function __construct(private UnitSubtypeService $subtypes) {}

    public function store(StoreUnitSubtypeRequest $request, Unit $unit): JsonResponse
    {
        $actor = $request->user();

        assert($actor instanceof User);

        $subtype = $this->subtypes->create($actor, $unit, $request->payload());

        return UnitSubtypeResource::make($subtype)
            ->response()
            ->setStatusCode(201);
    }

    public function update(UpdateUnitSubtypeRequest $request, Unit $unit, UnitSubtype $subtype): UnitSubtypeResource
    {
        $this->ensureBelongsToUnit($unit, $subtype);

        $subtype = $this->subtypes->update($subtype, $request->payload());

        return UnitSubtypeResource::make($subtype);
    }

    public function destroy(Unit $unit, UnitSubtype $subtype): Response
    {
        $this->ensureBelongsToUnit($unit, $subtype);
        $this->subtypes->delete($subtype);

        return response()->noContent();
    }

    private function ensureBelongsToUnit(Unit $unit, UnitSubtype $subtype): void
    {
        abort_unless($subtype->unit_id === $unit->id, 404);
    }
}
