<?php
/**
 * Formidable REST resource access policy.
 *
 * @package EntryFoundry
 */

namespace EntryFoundry\Formidable;

/**
 * Resolves Formidable resources and enforces their relationships.
 *
 * All Formidable model calls live in this integration boundary so REST
 * controllers do not need to know how Formidable stores forms or entries.
 */
final class FormidableAccessPolicy {

	/**
	 * Authorize access to an optional Formidable form.
	 *
	 * @param \WP_REST_Request $request REST request.
	 * @return true|\WP_Error
	 */
	public function authorize_form_request( \WP_REST_Request $request ) {
		if ( ! $request->has_param( 'source_id' ) ) {
			return true;
		}

		return $this->assert_form_exists( (int) $request->get_param( 'source_id' ) );
	}

	/**
	 * Authorize access to a Formidable form and optional entry.
	 *
	 * @param \WP_REST_Request $request REST request.
	 * @return true|\WP_Error
	 */
	public function authorize_entry_request( \WP_REST_Request $request ) {
		$source_id  = (int) $request->get_param( 'source_id' );
		$form_check = $this->assert_form_exists( $source_id );

		if ( is_wp_error( $form_check ) || ! $request->has_param( 'entry_id' ) ) {
			return $form_check;
		}

		if ( ! class_exists( 'FrmEntry' ) ) {
			return $this->unavailable_error();
		}

		$entry = \FrmEntry::getOne( (int) $request->get_param( 'entry_id' ), false );
		if ( ! is_object( $entry ) || (int) ( $entry->form_id ?? 0 ) !== $source_id ) {
			return new \WP_Error(
				'entryfoundry_formidable_entry_not_found',
				__( 'The requested Formidable entry was not found for this form.', 'entryfoundry-pdf-builder-for-formidable-forms' ),
				array( 'status' => 404 )
			);
		}

		return true;
	}

	/**
	 * Verify that a Formidable form exists.
	 *
	 * @param int $source_id Formidable form ID.
	 * @return true|\WP_Error
	 */
	private function assert_form_exists( int $source_id ) {
		if ( ! class_exists( 'FrmForm' ) ) {
			return $this->unavailable_error();
		}

		$form = \FrmForm::getOne( $source_id );
		if ( ! is_object( $form ) || (int) ( $form->id ?? 0 ) !== $source_id ) {
			return new \WP_Error(
				'entryfoundry_formidable_form_not_found',
				__( 'The requested Formidable form was not found.', 'entryfoundry-pdf-builder-for-formidable-forms' ),
				array( 'status' => 404 )
			);
		}

		return true;
	}

	/**
	 * Build the stable error used when Formidable is inactive or unavailable.
	 *
	 * @return \WP_Error
	 */
	private function unavailable_error(): \WP_Error {
		return new \WP_Error(
			'entryfoundry_formidable_unavailable',
			__( 'Formidable Forms is unavailable, so EntryFoundry cannot load form data.', 'entryfoundry-pdf-builder-for-formidable-forms' ),
			array( 'status' => 503 )
		);
	}
}
