<?php

namespace App\Services;

use App\Models\City;
use App\Models\State;
use Illuminate\Database\Eloquent\Collection;

class CityService
{
    public function getAll(): Collection
    {
        return City::query()->orderBy('name', 'asc')->get();
    }

    public function findById(int $id): ?City
    {
        return City::find($id);
    }

    public function create(array $data): City
    {
        return City::create($data);
    }

    public function update(int $id, array $data): ?City
    {
        $model = $this->findById($id);

        if (! $model) {
            return null;
        }

        $model->update($data);

        return $model->fresh();
    }

    public function delete(int $id): bool
    {
        $model = $this->findById($id);

        if (! $model) {
            return false;
        }

        return $model->delete();
    }

    //

    public function findStateCityByDescription(string $state, string $city): ?array
    {
        $state = State::query()
            ->where('code', $state)
            ->select(
                'name as label',
                'id as value',
            )
            ->first();

        $city = City::query()
            ->where('state_id', $state->value)
            ->where('name', $city)
            ->select(
                'name as label',
                'id as value',
                'state_id',
            )
            ->first();

        return [
            'state' => $state,
            'city'  => $city,
        ];
    }
}
