<?php

namespace App\Services;

use App\Models\City;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Database\Eloquent\Model;

trait CityService
{
    /**
     * Store new record
     *
     * @param array $data
     * @return Builder|Model
     */
    public static function store(array $data): Model|Builder
    {
        return City::query()->create($data);
    }

    /**
     * Update existing record
     *
     * @param array $data
     * @return mixed
     */
    public function updateService(array $data): mixed
    {
        return tap($this)->update($data);
    }

    /**
     * Create city
     *
     * @param array $data
     * @return Builder|Model
     */
    public static function createCity(array $data): Model|Builder
    {
        return self::store([
            "designation" => $data["designation"],
            "code" => $data["code"],
            "country_id" => $data["country_id"],
        ]);
    }

    /**
     * Get cities by country
     *
     * @param int $countryId
     * @return Builder[]|Collection
     */
    public static function getByCountry(int $countryId): Collection|array
    {
        $cities =  City::query()->where('country_id', $countryId)->get();

        $cityArray =  array();
        foreach ($cities as $city) {
            $cityArray[] = array(
                "id" => $city->{"id"},
                "code" => $city->{"code"},
                "designation" => $city->{"designation"},
            );
        }

        return $cityArray;
    }

    /**
     * Get by country id and city name
     *
     * @param int $countyId
     * @param string $cityName
     * @return Model|Builder|null
     */
    public static function getByCountryIdAndCityName(int $countyId, string $cityName ): Model|Builder|null
    {
        return City::query()->where("country_id", $countyId)->where("designation", $cityName)->first();
    }
}
