<?php

namespace App\Http\Controllers;

use App\Http\Requests\CityRequest;
use App\Http\Resources\CityResource;
use App\Services\CityService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class CityController extends Controller
{
    public function __construct(protected CityService $service) {}

    public function index(): JsonResponse
    {
        $items = $this->service->getAll();

        return $this->successResponse(
            payload: CityResource::collection($items),
        );
    }

    public function store(CityRequest $request): JsonResponse
    {
        $item = $this->service->create($request->validated());

        return $this->successResponse(
            payload: new CityResource($item),
            message: __('messages.created'),
            code:    201,
        );
    }

    public function show(int $id): JsonResponse
    {
        $item = $this->service->findById($id);

        return $this->successResponse(payload: new CityResource($item));
    }

    public function update(CityRequest $request, int $id): JsonResponse
    {
        $item = $this->service->update($id, $request->validated());

        return $this->successResponse(
            payload: new CityResource($item),
            message: __('messages.updated'),
        );
    }

    public function destroy(int $id): JsonResponse
    {
        $this->service->delete($id);

        return $this->successResponse(
            message: __('messages.deleted'),
            code:    204,
        );
    }

    //

    public function searchStateCityByDescription(Request $request): JsonResponse
    {
        $state = $request->query('stateUf');
        $city  = $request->query('cityName');

        $result = $this->service->findStateCityByDescription($state, $city);

        return $this->successResponse(
            payload: $result,
        );
    }
}
