<?php

declare(strict_types=1);

namespace App\Http\Controllers\Api\V1;

use App\Http\Controllers\Controller;
use App\Http\Requests\StoreRegionRequest;
use App\Http\Requests\UpdateRegionRequest;
use App\Http\Resources\RegionResource;
use App\Models\Region;
use Illuminate\Http\JsonResponse;

class RegionController extends Controller
{
    public function index(): JsonResponse
    {
        $regions = Region::query()->withCount('branches')->orderBy('name')->get();

        return RegionResource::collection($regions)->response();
    }

    public function store(StoreRegionRequest $request): RegionResource
    {
        $region = Region::create($request->validated());

        return new RegionResource($region);
    }

    public function update(UpdateRegionRequest $request, Region $region): RegionResource
    {
        $region->update($request->validated());

        return new RegionResource($region);
    }

    public function destroy(Region $region): JsonResponse
    {
        $this->authorize('delete', $region);

        if ($region->branches()->exists()) {
            return response()->json(['message' => 'Cannot delete a region that has branches.'], 409);
        }

        $region->delete();

        return response()->json(null, 204);
    }
}
