<?php

namespace App\Modules\ExternalUser\Application;

use App\Modules\External\Domain\IdExternal;
use App\Modules\ExternalUser\Domain\EasyExternalUser;
use App\Modules\ExternalUser\Domain\ExternalUser;
use App\Modules\ExternalUser\Domain\ExternalUserGender;
use App\Modules\ExternalUser\Domain\ExternalUserLastName;
use App\Modules\ExternalUser\Domain\ExternalUserName;
use App\Modules\ExternalUser\Domain\ExternalUserNickName;
use App\Modules\ExternalUser\Domain\ExternalUserRepository;
use App\Modules\ExternalUser\Domain\ExternalUserStatus;
use App\Modules\ExternalUser\Domain\IdExternalUser;

class ExternalUserInsertOrUpdater
{
    private ExternalUserRepository $repository;

    public function __construct(ExternalUserRepository $repository)
    {
        $this->repository = $repository;
    }

    public function __invoke(EasyExternalUser $model, IdExternal $idExternal): IdExternalUser
    {
        if ($model->getId()->value() === 0) {
            $insert = $this->repository->insert(
                new ExternalUser(
                    $model->getName(),
                    $model->getLastName(),
                    $model->getNickName(),
                    new ExternalUserGender(ExternalUserGender::MALE),
                    new ExternalUserStatus(ExternalUserStatus::ACTIVE),
                    $idExternal
                )
            );
            return new IdExternalUser($insert['Response_Data']['Id']);
        } else {
            $response = $this->repository->index($model->getId());
            $index = $response['Response_Data'][0];
            $this->repository->update(
                new ExternalUser(
                    new ExternalUserName($index->ExternalUser_Name),
                    new ExternalUserLastName($index->ExternalUser_LastName),
                    new ExternalUserNickName($index->ExternalUser_NickName),
                    new ExternalUserGender($index->ExternalUser_Gender),
                    new ExternalUserStatus($index->ExternalUser_Status),
                    new IdExternal($index->Id_External),
                    new IdExternalUser($index->Id_ExternalUser)
                )
            );
            return $model->getId();
        }
    }
}
