<?php
/**
 * Postomatic Plugin - Shared helpers for Product Source implementations.
 *
 * @package  Postomatic
 * @category Plugin
 * @license  GPL-2.0-or-later https://www.gnu.org/licenses/gpl-2.0.html
 * @link     https://buildomatics.com/postomatics
 * @since    1.3.0
 */

namespace Postomatic\Api;

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

/**
 * Product_Source_Abstract.
 *
 * Base class shared by every concrete Product_Source implementation. It only
 * contains platform-agnostic helpers (pagination shape, empty-result shape);
 * all platform-specific data fetching stays in the concrete classes.
 *
 * @since 1.3.0
 */
abstract class Product_Source_Abstract implements Product_Source_Interface {

	/**
	 * Build the normalized empty response shape.
	 *
	 * @param int $page     Current page number.
	 * @param int $per_page Number of products per page.
	 *
	 * @return array{products: array<int, array<string, mixed>>, pagination: array{total:int, per_page:int, current_page:int, total_pages:int}}
	 */
	protected function empty_result( int $page, int $per_page ): array {
		return array(
			'products'   => array(),
			'pagination' => array(
				'total'        => 0,
				'per_page'     => $per_page,
				'current_page' => $page,
				'total_pages'  => 0,
			),
		);
	}

	/**
	 * Build the normalized pagination block.
	 *
	 * @param int $total    Total number of matching products.
	 * @param int $page     Current page number.
	 * @param int $per_page Number of products per page.
	 *
	 * @return array{total:int, per_page:int, current_page:int, total_pages:int}
	 */
	protected function build_pagination( int $total, int $page, int $per_page ): array {
		return array(
			'total'        => $total,
			'per_page'     => $per_page,
			'current_page' => $page,
			'total_pages'  => $per_page > 0 ? (int) ceil( $total / $per_page ) : 0,
		);
	}

	/**
	 * Build the normalized "product" shape used by the admin UI (list rows).
	 *
	 * @param int    $id           Product ID.
	 * @param string $name         Product name.
	 * @param string $price_html  Pre-formatted, HTML-safe price string for display.
	 * @param string $description Short description/excerpt.
	 * @param string $url         Public-facing product URL.
	 * @param string $image       Main image URL.
	 * @param array  $meta        Full normalized product meta (see build_product_meta()).
	 *
	 * @return array<string, mixed>
	 */
	protected function build_list_item( int $id, string $name, string $price_html, string $description, string $url, string $image, array $meta ): array {
		return array(
			'id'           => $id,
			'name'         => $name,
			'price'        => $price_html,
			'description'  => $description,
			'url'          => $url,
			'image'        => $image,
			'product-meta' => $meta,
		);
	}
}
