<?php
/**
 * Images REST API controller.
 *
 * @package PDFDraft
 */

namespace PDFDraft\Controllers\V1;

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

use PDFDraft\Contracts\Services\ImageServiceInterface;
use PDFDraft\Traits\Hooks;
use PDFDraft\Support\Validation\RequestValidator;

/**
 * Handles REST API requests for image uploads and management.
 */
class ImagesController extends \WP_REST_Controller {

	use Hooks;

	/**
	 * Image service instance.
	 *
	 * @var ImageServiceInterface
	 */
	private ImageServiceInterface $imageService;

	/**
	 * Constructor.
	 *
	 * @param ImageServiceInterface $imageService Image service dependency.
	 */
	public function __construct( ImageServiceInterface $imageService ) {
		$this->imageService = $imageService;
	}

	/**
	 * API namespace.
	 *
	 * @var string
	 */
	protected $namespace = 'pdfdraft/v1';

	/**
	 * REST base route.
	 *
	 * @var string
	 */
	protected $rest_base = 'images';

	/**
	 * Register REST API routes for images.
	 *
	 * @return void
	 */
	public function register_routes() {
		register_rest_route(
			$this->namespace,
			'/' . $this->rest_base,
			array(
				array(
					'methods'             => \WP_REST_Server::CREATABLE,
					'callback'            => array( $this, 'create_item' ),
					'permission_callback' => array( $this, 'create_item_permissions_check' ),
					'args'                => array(
						'basename' => array(
							'required' => true,
							'type'     => 'string',
						),
						'content'  => array(
							'required' => true,
							'type'     => 'string',
						),
					),
				),
			)
		);
		register_rest_route(
			$this->namespace,
			'/' . $this->rest_base . '/(?P<basename>[a-zA-Z0-9_-]+)',
			array(
				array(
					'methods'             => \WP_REST_Server::READABLE,
					'callback'            => array( $this, 'get_item' ),
					'permission_callback' => array( $this, 'get_item_permissions_check' ),
					'args'                => array(
						'basename' => array(
							'required'          => true,
							'type'              => 'string',
							'sanitize_callback' => 'sanitize_text_field',
						),
					),
				),
				array(
					'methods'             => \WP_REST_Server::DELETABLE,
					'callback'            => array( $this, 'delete_item' ),
					'permission_callback' => array( $this, 'delete_item_permissions_check' ),
					'args'                => array(
						'basename' => array(
							'required'          => true,
							'type'              => 'string',
							'sanitize_callback' => 'sanitize_text_field',
						),
					),
				),
			)
		);
	}

	/**
	 * Check permissions for creating an image.
	 *
	 * @param \WP_REST_Request $request Full details about the request.
	 * @return true|\WP_Error True if allowed, WP_Error otherwise.
	 */
	public function create_item_permissions_check( $request ) {
		if ( ! current_user_can( 'upload_files' ) ) {
			return new \WP_Error(
				'rest_forbidden',
				__( 'You do not have permission to upload files.', 'pdfdraft' ),
				array( 'status' => 403 )
			);
		}
		return true;
	}

	/**
	 * Check permissions for retrieving an image.
	 *
	 * @param \WP_REST_Request $request Full details about the request.
	 * @return true|\WP_Error True if allowed, WP_Error otherwise.
	 */
	public function get_item_permissions_check( $request ) {
		if ( ! current_user_can( 'read' ) ) {
			return new \WP_Error(
				'rest_forbidden',
				__( 'You do not have permission to view files.', 'pdfdraft' ),
				array( 'status' => 403 )
			);
		}
		return true;
	}

	/**
	 * Check permissions for deleting an image.
	 *
	 * @param \WP_REST_Request $request Full details about the request.
	 * @return true|\WP_Error True if allowed, WP_Error otherwise.
	 */
	public function delete_item_permissions_check( $request ) {
		if ( ! current_user_can( 'delete_posts' ) ) {
			return new \WP_Error(
				'rest_forbidden',
				__( 'You do not have permission to delete files.', 'pdfdraft' ),
				array( 'status' => 403 )
			);
		}
		return true;
	}

	/**
	 * Create a new image from a data URL.
	 *
	 * @param \WP_REST_Request $request Full details about the request.
	 * @return \WP_REST_Response|\WP_Error Response object or error.
	 */
	public function create_item( $request ) {
		$basename = $request->get_param( 'basename' );
		$content  = $request->get_param( 'content' );

		try {
			RequestValidator::requireFields(
				array(
					'basename' => $basename,
					'content'  => $content,
				),
				array( 'basename', 'content' )
			);
		} catch ( \PDFDraft\Exceptions\ValidationException $e ) {
			return new \WP_Error(
				'validation_error',
				__( 'Validation failed.', 'pdfdraft' ),
				array(
					'status' => 400,
					'errors' => $e->getErrors(),
				)
			);
		}

		$result = $this->imageService->saveFromDataUrl( $basename, $content );

		if ( false === $result ) {
			return new \WP_Error(
				'save_error',
				__( 'Failed to save image.', 'pdfdraft' ),
				array( 'status' => 400 )
			);
		}

		return new \WP_REST_Response(
			array(
				'message'     => __( 'Image uploaded successfully.', 'pdfdraft' ),
				'basename'    => $basename,
				'url'         => $result['url'],
				'size'        => $result['size'],
				'modified_at' => $result['modified_at'],
			),
			201
		);
	}

	/**
	 * Retrieve a single image by basename.
	 *
	 * @param \WP_REST_Request $request Full details about the request.
	 * @return \WP_REST_Response|\WP_Error Response object or error.
	 */
	public function get_item( $request ) {
		$basename = $request->get_param( 'basename' );
		if ( ! $this->imageService->exists( $basename ) ) {
			return new \WP_Error(
				'image_not_found',
				__( 'Image not found.', 'pdfdraft' ),
				array( 'status' => 404 )
			);
		}
		$url  = $this->imageService->getUrl( $basename );
		$size = $this->imageService->getSize( $basename );
		return rest_ensure_response(
			array(
				'basename' => $basename,
				'url'      => $url,
				'size'     => $size,
			)
		);
	}

	/**
	 * Delete an image by basename.
	 *
	 * @param \WP_REST_Request $request Full details about the request.
	 * @return \WP_REST_Response|\WP_Error Response object or error.
	 */
	public function delete_item( $request ) {
		$basename = $request->get_param( 'basename' );

		if ( ! $this->imageService->exists( $basename ) ) {
			return new \WP_Error(
				'image_not_found',
				__( 'Image not found.', 'pdfdraft' ),
				array( 'status' => 404 )
			);
		}

		$result = $this->imageService->delete( $basename );

		if ( ! $result ) {
			return new \WP_Error(
				'delete_error',
				__( 'Failed to delete image.', 'pdfdraft' ),
				array( 'status' => 500 )
			);
		}

		return new \WP_REST_Response(
			array(
				'message'  => __( 'Image deleted successfully.', 'pdfdraft' ),
				'basename' => $basename,
			),
			200
		);
	}
}
