<?php

namespace Waypoint\Agent\Rest\Handler;

class Media {

	public function handle( \WP_REST_Request $request ): \WP_REST_Response {
		$source_url = esc_url_raw( (string) $request->get_param( 'source_url' ) );

		if ( '' === $source_url ) {
			return rest_ensure_response( new \WP_Error(
				'rest_missing_callback_param',
				'Missing parameter(s): source_url',
				[ 'status' => 400 ]
			) );
		}

		if ( ! function_exists( 'media_sideload_image' ) ) {
			require_once ABSPATH . 'wp-admin/includes/media.php';
			require_once ABSPATH . 'wp-admin/includes/file.php';
			require_once ABSPATH . 'wp-admin/includes/image.php';
		}

		$alt_text       = sanitize_text_field( (string) ( $request->get_param( 'alt_text' ) ?? '' ) );
		$slot_reference = sanitize_text_field( (string) ( $request->get_param( 'slot_reference' ) ?? '' ) );
		$attach_to      = (int) ( $request->get_param( 'attach_to_post_id' ) ?? 0 );

		$attachment_id = media_sideload_image( $source_url, $attach_to ?: null, $alt_text, 'id' );

		if ( is_wp_error( $attachment_id ) ) {
			return rest_ensure_response( new \WP_Error(
				'waypoint_agent_sideload_failed',
				$attachment_id->get_error_message(),
				[ 'status' => 500 ]
			) );
		}

		if ( '' !== $alt_text ) {
			update_post_meta( $attachment_id, '_wp_attachment_image_alt', $alt_text );
		}
		if ( '' !== $slot_reference ) {
			update_post_meta( $attachment_id, '_waypoint_slot_ref', $slot_reference );
		}

		return rest_ensure_response( [
			'attachment_id'  => $attachment_id,
			'url'            => wp_get_attachment_url( $attachment_id ),
			'slot_reference' => '' !== $slot_reference ? $slot_reference : null,
		] );
	}
}
