<?php
/**
 * BookiFlex Payment Extension
 *
 * @package    BookiFlex
 * @subpackage Payment
 * @author     BookiFlex
 * @copyright  Copyright (c) 2025 BookiFlex
 * @license    GPL-2.0-or-later
 *
 * @link       https://bookiflex.com
 */


declare(strict_types=1);
namespace BookiFlex\Extensions\Payment\Infrastructure\Payum;

use BookiFlex\Extensions\Payment\Model\Payment;
use Cycle\ORM\ORM;
use Payum\Core\Model\Identity;
use Payum\Core\Storage\AbstractStorage;
use Payum\Core\Storage\IdentityInterface;
use Cycle\ORM\EntityManagerInterface;

defined( 'ABSPATH' ) || exit;

/**
 * Storage for Cycle ORM.
 */
class CycleStorage extends AbstractStorage
{
    /**
     * @var EntityManagerInterface
     */
    protected EntityManagerInterface $entityManager;
    private ORM $ORM;

    /**
     * @param EntityManagerInterface $objectManager
     * @param ORM $ORM
     * @param string $modelClass
     */
    public function __construct(EntityManagerInterface $objectManager, ORM $ORM, string $modelClass)
    {
        parent::__construct($modelClass);
        $this->entityManager = $objectManager;
        $this->ORM           = $ORM;
    }

    public function findBy(array $criteria): array
    {
        return $this->ORM->getRepository($this->modelClass)->findOne($criteria);
    }

    protected function doFind(mixed $id): ?object
    {
        if ($id instanceof IdentityInterface) {
            $id = $id->getId();
        }
        return $this->ORM->getRepository($this->modelClass)->findByPK($id);
    }

    protected function doUpdateModel($model): object
    {
        $this->entityManager->persist($model);
        $this->entityManager->run();

        return $model;
    }

    protected function doDeleteModel($model): void
    {
        $this->entityManager->delete($model);
        $this->entityManager->run();
    }

    protected function doGetIdentity($model): IdentityInterface
    {
        //        $schema     = $this->ORM->getSchema();
        //        $primaryKey = $schema->define($model::class, SchemaInterface::PRIMARY_KEY);
        //        $id         = $model->get . mb_strtoupper($primaryKey) . '()';

        //        if (is_array($primaryKey)) {
        //            throw new LogicException('Storage does not support composite primary ids');
        //        }
        return new Identity($model->getId(), Payment::class);
    }
}
