<?php

namespace WarrantyCart\REST;

use WP_Error;
use WP_REST_Controller;
use WP_REST_Request;
use WP_REST_Response;

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

/**
 * Base REST API Controller
 *
 * Provides common functionality for all REST API controllers.
 */
abstract class BaseController extends WP_REST_Controller {

	/**
	 * Namespace for the REST API
	 *
	 * @var string
	 */
	protected $namespace = 'warranty-cart/v1';

	/**
	 * REST base for the controller
	 *
	 * @var string
	 */
	protected $rest_base = '';

	/**
	 * Check if user has admin permission
	 *
	 * @param WP_REST_Request $request Request object.
	 * @return bool|WP_Error
	 */
	public function check_admin_permission( WP_REST_Request $request ) {
		if ( ! \current_user_can( 'manage_options' ) ) {
			return new WP_Error(
				'rest_forbidden',
				\__( 'You do not have permission to access this endpoint.', 'warranty-cart' ),
				array( 'status' => 403 )
			);
		}

		return true;
	}

	/**
	 * Allow public access (for cart operations)
	 *
	 * @param WP_REST_Request $request Request object.
	 * @return bool
	 */
	public function check_public_permission( WP_REST_Request $request ) {
		return true;
	}

	/**
	 * Create success response
	 *
	 * Generates a standardized success response for REST API endpoints.
	 *
	 * @param mixed $data    Response data.
	 * @param int   $status  HTTP status code.
	 * @return WP_REST_Response REST response object.
	 */
	protected function success_response( $data = null, int $status = 200 ): WP_REST_Response {
		$response = array(
			'success' => true,
		);

		if ( null !== $data ) {
			$response['data'] = $data;
		}

		return new WP_REST_Response( $response, $status );
	}

	/**
	 * Create error response
	 *
	 * Generates a standardized error response for REST API endpoints.
	 *
	 * @param string $message Error message.
	 * @param int    $status  HTTP status code.
	 * @param string $code    Error code.
	 * @return WP_Error REST error object.
	 */
	protected function error_response( string $message, int $status = 400, string $code = 'api_error' ): WP_Error {
		return new WP_Error(
			$code,
			$message,
			array( 'status' => $status )
		);
	}
}
