<?php
/**
 * @package Hafenstudios\Kurato
 */

namespace Hafenstudios\Kurato\Rest;

use Hafenstudios\Kurato\Db\StageRepository;

defined( 'ABSPATH' ) || exit;

/**
 * REST: Pipeline-Stufen (`kurato/v1/stages`), lesend fuer Filter und das
 * Kanban-Board (K3). Cap hs_view_contacts.
 */
final class StagesController {

	public const REST_NAMESPACE = 'kurato/v1';

	private StageRepository $stages;

	/**
	 * @param StageRepository $stages Stufen-Repository.
	 */
	public function __construct( StageRepository $stages ) {
		$this->stages = $stages;
	}

	/**
	 * Registriert die Route.
	 *
	 * @return void
	 */
	public function register_routes(): void {
		register_rest_route(
			self::REST_NAMESPACE,
			'/stages',
			array(
				'methods'             => \WP_REST_Server::READABLE,
				'callback'            => array( $this, 'list_stages' ),
				'permission_callback' => static function () {
					if ( current_user_can( 'hs_view_contacts' ) ) {
						return true;
					}
					return new \WP_Error(
						'kurato_forbidden',
						__( 'Sie haben keine Berechtigung, die Pipeline einzusehen.', 'kurato' ),
						array( 'status' => rest_authorization_required_code() )
					);
				},
			)
		);
	}

	/**
	 * GET /stages - Stufen mit Kontaktzahl.
	 *
	 * @return \WP_REST_Response
	 */
	public function list_stages(): \WP_REST_Response {
		$counts = $this->stages->contact_counts();
		$stages = array_map(
			static function ( array $stage ) use ( $counts ): array {
				$stage['count'] = $counts[ $stage['id'] ] ?? 0;
				return $stage;
			},
			$this->stages->all()
		);
		return new \WP_REST_Response( $stages, 200 );
	}
}
