<?php

namespace App\Modules\HR\Employees\Services;

use App\Modules\Platform\Geography\Models\GeoCity;
use App\Modules\Platform\Geography\Models\GeoCountry;
use App\Modules\Platform\Geography\Models\GeoRegion;
use App\Support\LocalizedName;

final class EmployeeAddressGeoResolver
{
    /**
     * @param  array<string, mixed>  $data
     * @return array<string, string|int|null>
     */
    public function toPersistenceArray(array $data): array
    {
        $countryId = ! empty($data['address_country_id']) ? (int) $data['address_country_id'] : null;
        $regionId = ! empty($data['address_region_id']) ? (int) $data['address_region_id'] : null;
        $cityId = ! empty($data['address_city_id']) ? (int) $data['address_city_id'] : null;

        $country = $countryId ? GeoCountry::query()->find($countryId) : null;
        $region = $regionId ? GeoRegion::query()->find($regionId) : null;
        $city = $cityId ? GeoCity::query()->find($cityId) : null;

        return [
            'country_id' => $countryId,
            'region_id' => $regionId,
            'city_id' => $cityId,
            'country' => $country ? LocalizedName::fromModel($country) : null,
            'state' => $region ? LocalizedName::fromModel($region) : null,
            'city' => $city ? LocalizedName::fromModel($city) : null,
            'postal_code' => isset($data['address_postal_code']) ? (string) $data['address_postal_code'] : null,
            'street' => isset($data['address_street']) ? (string) $data['address_street'] : null,
            'building_number' => isset($data['address_building_number'])
                ? (string) $data['address_building_number']
                : null,
            'location_link' => isset($data['address_location_link'])
                ? (string) $data['address_location_link']
                : null,
        ];
    }
}
