<?php

namespace Shm\ShmPayment\TBankPayment\TBankCollections;

use Shm\Collection\Collection;
use Shm\Shm;
use Shm\ShmPayment\TBankPayment\TBankNominal\TBankNominal;
use Shm\ShmTypes\StructureType;

class TNominalCustomers extends Collection
{

    public function schema(): StructureType
    {
        return Shm::structure([

            "TerminalKey" => Shm::static(TBankNominal::$TerminalKey),
            "CustomerKey" => Shm::string()->title("Идентификатор покупателя в системе мерчанта"),
            "Phone" => Shm::string()->title("Телефон покупателя"),
            "response" => Shm::structure([
                "TerminalKey" => Shm::string()->title("Идентификатор терминала"),
                "CustomerKey" => Shm::string()->title("Идентификатор покупателя в системе мерчанта"),
                "ErrorCode" => Shm::string()->title("Код ошибки"),
                "Success" => Shm::boolean()->title("Успешность операции"),
                "Message" => Shm::string()->title("Краткое описание ошибки."),
                "Details" => Shm::string()->title("Подробное описание ошибки."),
            ])->title("Ответ от сервиса"),
        ]);
    }


    private static function generateCustomerKey($phone)
    {
        return hash('sha256', $phone . TBankNominal::$TerminalKey);
    }

    public static function getCustomerKey($phone)
    {


        if (is_numeric($phone)) {
            $phone = '+7' . $phone;
        }


        $customer = self::findOne([
            'Phone' => $phone,
        ]);
        if ($customer) {
            return $customer['CustomerKey'];
        }


        $customerKey = self::generateCustomerKey($phone);



        $newCustomer = [
            'TerminalKey' => TBankNominal::$TerminalKey,
            'Phone' => $phone,
            'CustomerKey' => $customerKey,

        ];

        $response =  TBankNominal::sendTerminalRequest('AddCustomer',  $newCustomer);

        $isSuccess = $response['Success'] ?? false;

        if ($isSuccess) {
            self::insertOne([
                ...$newCustomer,
                'response' => $response,
            ]);

            return $customerKey;
        } else {

            Shm::error("Ошибка при создании покупателя");
        }


        return null;
    }
}