<?php
declare(strict_types=1);

namespace Wohno\Plugin\Shortcode;

use Wohno\Plugin\Api\Client;
use Wohno\Plugin\Api\ListingQuery;
use Wohno\Plugin\Render\ListingsRenderer;

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

/**
 * `[wohno_listing id="…"]`
 *
 * Embeds a single listing's teaser card (linking to the canonical detail page on
 * wohno.de). Server-side fetch + native render.
 */
final class ListingShortcode {

	/**
	 * Constructor.
	 *
	 * @param Client           $client   API client.
	 * @param ListingsRenderer $renderer HTML renderer.
	 */
	public function __construct(
		private readonly Client $client,
		private readonly ListingsRenderer $renderer
	) {
	}

	/**
	 * Register the `[wohno_listing]` shortcode.
	 *
	 * @return void
	 */
	public function register(): void {
		add_shortcode( 'wohno_listing', array( $this, 'render' ) );
	}

	/**
	 * Render the shortcode output.
	 *
	 * @param array<string, mixed>|string $atts Shortcode attributes.
	 * @return string Escaped HTML.
	 */
	public function render( $atts ): string {
		$atts = shortcode_atts(
			array( 'id' => '' ),
			is_array( $atts ) ? $atts : array(),
			'wohno_listing'
		);

		$id = ListingQuery::sanitize_id( $atts['id'] );
		if ( '' === $id ) {
			return current_user_can( 'edit_posts' )
				? '<p class="wohno-error">' . esc_html__( 'Bitte eine Inserat-ID angeben: [wohno_listing id="…"].', 'wohno' ) . '</p>'
				: '';
		}

		$result = $this->client->listing( $id );
		if ( is_wp_error( $result ) ) {
			return current_user_can( 'edit_posts' )
				? '<p class="wohno-error">' . esc_html( $result->get_error_message() ) . '</p>'
				: '';
		}

		return $this->renderer->single( $result );
	}
}
