<?php

namespace Fifa\ConnectId\Sdk\ExceptionHandler\Handler\MergeOperations;

use Fifa\ConnectId\Sdk\Api\ApiException;
use Fifa\ConnectId\Sdk\Exception\FifaConnectIdException;

/**
 * Class MergeOperation
 * @package Fifa\ConnectId\Sdk\ExceptionHandler\Handler\MergeOperations
 */
abstract class MergeOperation
{
    /**
     * @var string
     */
    const MERGED_INTO_HEADER_NAME = 'X-Merged-Into';

    /**
     * String representation of the object
     *
     * @return string
     */
    public function __toString()
    {
        return 'MERGED_INTO_HEADER_NAME: ' . self::MERGED_INTO_HEADER_NAME;
    }

    /**
     * Handler method for ApiExceptions
     *
     * @param ApiException $e
     * @param string $responseType - class name of expected response type
     * @param string $exceptionType - class name of exception that will be returned
     * @return FifaConnectIdException
     */
    protected function handleInternal(ApiException $e, string $responseType, string $exceptionType): ?FifaConnectIdException
    {
        $requestedData = $e->getResponseObject();
        $responseHeaders = $e->getResponseHeaders();
        $primaryFIFAId = $responseHeaders[self::MERGED_INTO_HEADER_NAME] ?? null;

        if ($e->getCode() == 301 && $requestedData instanceof $responseType && !is_null($primaryFIFAId)) {

            $message = sprintf($this->getMessagePattern(), $e->getCode(), $primaryFIFAId);
            return new $exceptionType($e, $message, $primaryFIFAId, $requestedData);
        }

        return null;
    }

    /**
     * Returns string pattern for message that will be filled with exception code and FIFA ID
     *
     * @return string
     */
    abstract protected function getMessagePattern(): string;
}