<?php
/**
 * Abstract post type base class.
 *
 * @package PDFDraft
 */

namespace PDFDraft\PostTypes;

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

use PDFDraft\Contracts\PostTypes\PostTypeInterface;
use PDFDraft\Traits\Hooks;

/**
 * Base class for custom post type registration.
 */
abstract class PostType implements PostTypeInterface {

	use Hooks;

	/**
	 * Get the post type slug.
	 *
	 * @return string
	 */
	abstract public function getPostType(): string;

	/**
	 * Get the post type registration arguments.
	 *
	 * @return array
	 */
	abstract public function getPostTypeArgs(): array;

	/**
	 * Register the post type with WordPress.
	 *
	 * @return void
	 *
	 * @throws \RuntimeException If post type registration fails.
	 */
	public function register(): void {
		if ( post_type_exists( $this->getPostType() ) ) {
			return;
		}

		/**
		 * Filter the post type registration arguments.
		 *
		 * @param array<string, mixed> $args      Post type arguments.
		 * @param string              $post_type Post type identifier.
		 */
		$args   = $this->applyFilters( "pdfdraft:{$this->getPostType()}:post-type:args", $this->getPostTypeArgs(), $this->getPostType() );
		$result = register_post_type( $this->getPostType(), $args );

		if ( is_wp_error( $result ) ) {
			throw new \RuntimeException(
				sprintf(
					'Failed to register post type "%s": %s',
					esc_html( $this->getPostType() ),
					esc_html( $result->get_error_message() )
				)
			);
		}

		$this->doAction( "pdfdraft:{$this->getPostType()}:post-type:registered", $this->getPostType() );
	}

	/**
	 * Check if the post type is registered.
	 *
	 * @return bool
	 */
	public function isRegistered(): bool {
		return post_type_exists( $this->getPostType() );
	}
}
