<?php
declare( strict_types=1 );

namespace FiboFilters\Sorting\Schema;

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

/**
 * Class CustomSortItemSchema
 */
class CustomSortItemSchema {
	public static function get( string $source = '' ): array {
		$base     = self::get_base_schema();
		$variants = self::get_variant_schemas();
		$variant  = $variants[ $source ] ?? [
			'properties' => [],
			'required'   => [],
		];

		$properties = array_merge( $base['properties'], $variant['properties'] );
		$required   = array_values( array_unique( array_merge( $base['required'], $variant['required'] ) ) );

		return [
			'type'                 => 'object',
			'properties'           => $properties,
			'required'             => $required,
			'additionalProperties' => false,
		];
	}

	public static function get_all_variants(): array {
		$variants = self::get_variant_schemas();

		$result = [];

		foreach ( array_keys( $variants ) as $variant_key ) {
			$result[] = self::get( $variant_key );
		}

		return $result;
	}

	private static function get_base_schema(): array {
		return [
			'properties' => [
				'value'  => [
					'type'      => 'string',
					'minLength' => 1,
				],
				'label'  => [
					'type'      => 'string',
					'minLength' => 1,
				],
				'source' => [
					'type' => 'string',
					'enum' => [ 'postmeta' ],
				],
				'type'   => [
					'type'    => 'string',
					'enum'    => [ 'numeric' ],
					'default' => 'numeric',
				],
				'order'  => [
					'type' => 'string',
					'enum' => [ 'asc', 'desc' ],
				],

			],
			'required'   => [ 'value', 'label', 'source', 'type', 'order' ],
		];
	}

	private static function get_variant_schemas(): array {
		return [
			'postmeta' => [
				'properties' => [
					'postmeta_key' => [
						'type'      => 'string',
						'minLength' => 1,
					],
				],
				'required'   => [ 'postmeta_key' ],
			],
		];
	}
}
