<?php
declare( strict_types=1 );

namespace BeyondSEO\Domain\Integrations\WordPress\Seo\Repo\InternalDB\WebPages;

if ( ! defined( 'ABSPATH' ) ) exit; // Exit if accessed directly

use BeyondSEO\Domain\Common\Repo\InternalDB\InternalDBEntity;
use BeyondSEO\Domain\Common\Repo\InternalDB\Models\InternalDBMetaTagModel;
use BeyondSEO\Domain\Integrations\WordPress\Seo\Entities\WebPages\Content\Elements\MetaTags\Social\WPWebPageSocialTitleMetaTag;
use BeyondSEO\Domain\Integrations\WordPress\Seo\Entities\WebPages\Content\Elements\MetaTags\WPWebPageMetaTag;
use BeyondSEO\Domain\Integrations\WordPress\Seo\Entities\WebPages\Content\Elements\WPWebPageTitle;
use BeyondSEO\Domain\Integrations\WordPress\Seo\Entities\WebPages\Content\WPWebPageContentMetaTags;
use BeyondSEODeps\DDD\Domain\Base\Entities\DefaultObject;
use BeyondSEODeps\DDD\Domain\Base\Entities\Entity;
use BeyondSEODeps\DDD\Domain\Base\Entities\LazyLoad\LazyLoad;
use BeyondSEODeps\DDD\Domain\Base\Repo\DB\Attributes\EntityCache;
use BeyondSEODeps\DDD\Domain\Base\Repo\DB\Doctrine\DoctrineQueryBuilder;
use BeyondSEODeps\DDD\Infrastructure\Cache\Cache;
use BeyondSEODeps\DDD\Infrastructure\Exceptions\BadRequestException;
use BeyondSEODeps\DDD\Infrastructure\Exceptions\InternalErrorException;
use BeyondSEODeps\Doctrine\DBAL\Exception;
use BeyondSEODeps\Doctrine\ORM\Mapping\MappingException;
use Psr\Cache\InvalidArgumentException;
use ReflectionException;

/**
 * Class InternalDBWPWebPageSocialMetaTagTitle
 * @method WPWebPageSocialTitleMetaTag find(DoctrineQueryBuilder|string|int $idOrQueryBuilder, bool $useEntityRegistryCache = false, ?InternalDBMetaTagModel &$loadedOrmInstance = null, bool $deferredCaching = false, array $initiatorClasses = [] )
 * @property InternalDBMetaTagModel $ormInstance
 */
#[EntityCache(useExtendedRegistryCache: false, ttl: 300, cacheGroup: Cache::CACHE_GROUP_PHPFILES, cacheScopes: [])]
class InternalDBWPWebPageSocialMetaTagTitle extends InternalDBEntity {
	public const BASE_ENTITY_CLASS = WPWebPageSocialTitleMetaTag::class;
	public const BASE_ORM_MODEL = InternalDBMetaTagModel::class;

    /**
     * @param WPWebPageContentMetaTags $initiatingEntity
     * @param LazyLoad $lazyloadAttributeInstance
     *
     * @return WPWebPageSocialTitleMetaTag|null
     * @throws BadRequestException
     * @throws Exception
     * @throws InternalErrorException
     * @throws InvalidArgumentException
     * @throws MappingException
     * @throws ReflectionException
     */
    public function lazyload(
        DefaultObject &$initiatingEntity,
        LazyLoad &$lazyloadAttributeInstance
    ): ?WPWebPageSocialTitleMetaTag {
        return $this->getMetaTagByTypeAndId($initiatingEntity->postId, WPWebPageMetaTag::TAG_TYPE_SOCIAL_TITLE, $lazyloadAttributeInstance->useCache);
    }

	/**
	 * Applies update/delete restrictions based on Auth::instance()->getAccount
	 *
	 * @param DoctrineQueryBuilder $queryBuilder
	 *
	 * @return bool
	 * @noinspection PhpMissingParentCallCommonInspection*/
	public static function applyUpdateRightsQuery(DoctrineQueryBuilder &$queryBuilder): bool
	{
		return false;
	}

    /**
     * @param bool $useEntityRegistryCache
     *
     * @return WPWebPageSocialTitleMetaTag|null
     * @throws ReflectionException
     */
	public function mapToEntity( bool $useEntityRegistryCache = false ): ?WPWebPageSocialTitleMetaTag
	{
        /** @var WPWebPageSocialTitleMetaTag $entity */
		$entity = parent::mapToEntity( $useEntityRegistryCache );

        $entity->id = $this->ormInstance->id;
        $entity->postId = $this->ormInstance->post_id;
        $entity->type = $this->ormInstance->type ?? WPWebPageTitle::TAG_TYPE_SOCIAL_TITLE;
        $entity->content = $this->ormInstance->content;
        $entity->template = $this->ormInstance->template;
        $entity->autoGenerated = $this->ormInstance->auto_generated;

        $entity->variables = $this->processVariablesFromJson($this->ormInstance->variables);
        $entity->uniqueKey = $this->ormInstance->unique_key;

		return $entity;
	}

    /**
     * @param Entity $entity
     *
     * @return bool
     * @throws ReflectionException
     */
	protected function mapToRepository(Entity &$entity): bool
	{
        /** @var WPWebPageSocialTitleMetaTag $entity */
		parent::mapToRepository($entity);
		$ormInstance = $this->ormInstance;

		if (isset($entity->id)) {
			$ormInstance->id = (int)$entity->id;
		}

		if (isset($entity->postId)) {
			$ormInstance->post_id = (int)$entity->postId;
		}

		$ormInstance->type = $entity->type ?? WPWebPageMetaTag::TAG_TYPE_SOCIAL_TITLE;
		$ormInstance->content = $entity->content ?? '';
		$ormInstance->template = $entity->formatTemplate() ?? '';
		$ormInstance->auto_generated = $entity->autoGenerated ?? false;

		if (isset($entity->variables)) {
			$ormInstance->variables = json_encode($entity->variables);
		}

		$ormInstance->unique_key = $entity->uniqueKey();
		$this->ormInstance = $ormInstance;

		return true;
	}

    /**
     * Retrieves a WPWebPageMetaTag entity by its ID.
     *
     * @param int $postId The ID of the post to retrieve.
     * @param string $type The type of the meta-tag to retrieve.
     * @param bool $useCache
     * @return WPWebPageSocialTitleMetaTag|null The WPWebPageMetaTag entity.
     * @throws BadRequestException
     * @throws InternalErrorException
     * @throws InvalidArgumentException
     * @throws ReflectionException
     * @throws Exception
     * @throws MappingException
     */
	public function getMetaTagByTypeAndId(int $postId, string $type, bool $useCache = false): ?WPWebPageSocialTitleMetaTag
    {
        $queryBuilder = self::createQueryBuilder();
		$queryBuilder
			->select('p')
			->from(InternalDBMetaTagModel::class, 'p')
			->where('p.post_id = :postId')
			->andWhere('p.type = :type')
			->setParameter('postId', $postId)
			->setParameter('type', $type);
        return $this->find($queryBuilder, $useCache);
	}
}