<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Http\Requests\Api\StoreUnitRequest;
use App\Http\Requests\Api\UpdateUnitRequest;
use App\Http\Resources\UnitResource;
use App\Models\Unit;
use App\Models\User;
use App\Services\UnitService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Resources\Json\AnonymousResourceCollection;
use Illuminate\Http\Response;

class UnitController extends Controller
{
    public function __construct(private UnitService $units) {}

    public function index(): AnonymousResourceCollection
    {
        return UnitResource::collection(
            Unit::query()
                ->with(['creator', 'subtypes'])
                ->withCount('bookings')
                ->orderBy('name')
                ->get(),
        );
    }

    public function store(StoreUnitRequest $request): JsonResponse
    {
        $actor = $request->user();

        assert($actor instanceof User);

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

        return UnitResource::make($unit->loadMissing(['creator', 'subtypes'])->loadCount('bookings'))
            ->response()
            ->setStatusCode(201);
    }

    public function show(Unit $unit): UnitResource
    {
        return UnitResource::make($unit->loadMissing(['creator', 'subtypes'])->loadCount('bookings'));
    }

    public function update(UpdateUnitRequest $request, Unit $unit): UnitResource
    {
        $unit = $this->units->update($unit, $request->payload());

        return UnitResource::make($unit->loadMissing(['creator', 'subtypes'])->loadCount('bookings'));
    }

    public function destroy(Unit $unit): Response
    {
        $this->units->delete($unit);

        return response()->noContent();
    }
}
