<?php

declare(strict_types=1);

namespace App\Services;

use App\Models\City;
use App\Utils;
use Illuminate\Contracts\Pagination\LengthAwarePaginator;

final class CityService
{
    public function paginateList(
        ?string $cityName,
        string $sort,
        string $sortType
    ): LengthAwarePaginator {
        $query = City::query();

        if ($cityName !== null && $cityName !== '') {
            $query->where('city_name', 'like', '%' . $cityName . '%');
        }

        $query->orderBy($sort, $sortType);

        return $query->paginate(Utils::item_per_page);
    }

    public function create(array $validated): City
    {
        return City::create($this->payload($validated));
    }

    public function update(City $city, array $validated): City
    {
        $city->fill($this->payload($validated));
        $city->save();

        return $city;
    }

    private function payload(array $validated): array
    {
        return [
            'city_name'    => $validated['city_name'],
            'print_layout' => $validated['print_layout'],
            'city_remarks' => $validated['city_remarks'] ?? null,
        ];
    }
}
