<?php

/*
 * This file is part of the Serenity package.
 *
 * (c) CP Creation <web@cpcreation.fr>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace CpCreation\VitiCore\Bridge\Doctrine\EventSubscriber;

use CpCreation\VitiCore\Behavior\HasGeocoder;
use Doctrine\Bundle\DoctrineBundle\Attribute\AsDoctrineListener;
use Doctrine\ORM\Events;
use Doctrine\Persistence\Event\LifecycleEventArgs;
use Geocoder\Model\Coordinates;
use Geocoder\Query\GeocodeQuery;
use Psr\Http\Client\ClientInterface;

#[AsDoctrineListener(event: Events::prePersist)]
#[AsDoctrineListener(event: Events::preUpdate)]
readonly class GeocoderSubscriber
{
    public function __construct(private string $apiKeyServerGooglemap, private ClientInterface $client)
    {
    }

    public function prePersist(LifecycleEventArgs $args): void
    {
        $entity = $args->getObject();
        if ($entity instanceof HasGeocoder) {
            $coordinates = $this->geocoder($entity);
            if ($coordinates) {
                $entity->setLat($coordinates->getLatitude());
                $entity->setLng($coordinates->getLongitude());
            }
        }
    }

    public function preUpdate(LifecycleEventArgs $args): void
    {
        $entity = $args->getObject();
        if ($entity instanceof HasGeocoder) {
            $coordinates = $this->geocoder($entity);
            if ($coordinates) {
                $entity->setLat($coordinates->getLatitude());
                $entity->setLng($coordinates->getLongitude());
            }
        }
    }

    private function geocoder(HasGeocoder $geocodable): ?Coordinates
    {
        $provider = new \Geocoder\Provider\GoogleMaps\GoogleMaps($this->client, null, $this->apiKeyServerGooglemap);
        $geocoder = new \Geocoder\StatefulGeocoder($provider, 'en');
        $result = $geocoder->geocodeQuery(GeocodeQuery::create($geocodable->getAddress().' '.$geocodable->getPostal().' '.$geocodable->getCity().' '.$geocodable->getCountry()));
        if ($result->isEmpty()) {
            return null;
        }

        return $result->first()->getCoordinates();
    }
}
