<?php

namespace Waypoint\Agent\Rest\Handler;

class Redirects {

	public function handle( \WP_REST_Request $request ): \WP_REST_Response {
		$from_raw = $request->get_param( 'from' );
		$to_raw   = $request->get_param( 'to' );

		$missing = [];
		if ( empty( $from_raw ) ) {
			$missing[] = 'from';
		}
		if ( empty( $to_raw ) ) {
			$missing[] = 'to';
		}
		if ( ! empty( $missing ) ) {
			return rest_ensure_response( new \WP_Error(
				'rest_missing_callback_param',
				sprintf( 'Missing parameter(s): %s', implode( ', ', $missing ) ),
				[ 'status' => 400 ]
			) );
		}

		if ( ! class_exists( 'Red_Item' ) ) {
			return rest_ensure_response( new \WP_Error(
				'waypoint_agent_redirection_unavailable',
				'The Redirection plugin is required for POST /redirects. Please install and activate it.',
				[ 'status' => 503 ]
			) );
		}

		$from        = '/' . ltrim( sanitize_text_field( (string) $from_raw ), '/' );
		$to          = esc_url_raw( (string) $to_raw );
		$code        = (int) ( $request->get_param( 'code' ) ?? 301 );
		$queued_only = null === $request->get_param( 'queued_only' ) ? true : (bool) $request->get_param( 'queued_only' );

		if ( ! in_array( $code, [ 301, 302, 307, 308 ], true ) ) {
			$code = 301;
		}

		$group_id = $this->ensure_redirect_group();
		if ( ! $group_id ) {
			return rest_ensure_response( new \WP_Error(
				'waypoint_agent_redirect_group_failed',
				'Could not create or find the Waypoint Agent redirect group.',
				[ 'status' => 500 ]
			) );
		}

		$item = \Red_Item::create( [
			'url'         => $from,
			'action_type' => 'url',
			'action_code' => $code,
			'action_data' => [ 'url' => $to ],
			'regex'       => false,
			'match_type'  => 'url',
			'status'      => $queued_only ? 'disabled' : 'enabled',
			'group_id'    => $group_id,
		] );

		if ( is_wp_error( $item ) ) {
			return rest_ensure_response( new \WP_Error(
				'waypoint_agent_redirect_failed',
				$item->get_error_message(),
				[ 'status' => 500 ]
			) );
		}
		if ( ! $item ) {
			return rest_ensure_response( new \WP_Error(
				'waypoint_agent_redirect_failed',
				'Failed to create redirect.',
				[ 'status' => 500 ]
			) );
		}

		return rest_ensure_response( [
			'redirect_id' => is_object( $item ) && method_exists( $item, 'get_id' ) ? $item->get_id() : null,
			'from'        => $from,
			'to'          => $to,
			'code'        => $code,
			'status'      => $queued_only ? 'queued' : 'active',
		] );
	}

	private function ensure_redirect_group(): int {
		if ( ! class_exists( 'Red_Group' ) ) {
			return 0;
		}
		global $wpdb;
		$table      = $wpdb->prefix . 'redirection_groups';
		$group_name = 'Waypoint Agent';

		$existing_id = $wpdb->get_var( $wpdb->prepare( "SELECT id FROM {$table} WHERE name = %s LIMIT 1", $group_name ) );
		if ( $existing_id ) {
			return (int) $existing_id;
		}

		$group = \Red_Group::create( $group_name, 1 );
		if ( $group && method_exists( $group, 'get_id' ) ) {
			return (int) $group->get_id();
		}
		return 0;
	}
}
