<?php

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

/**
 * Permission callback for REST API routes
 * 
 * @return boolean Whether the user can access the endpoint
 */
function content_craft_ai_permission_callback()
{
    // Allow unauthenticated access but verify nonce
    $nonce_verified = wp_verify_nonce(
        isset($_SERVER['HTTP_X_WP_NONCE']) ? sanitize_text_field(wp_unslash($_SERVER['HTTP_X_WP_NONCE'])) : '',
        'wp_rest'
    );

    if (!$nonce_verified) {
        // For debugging purposes
        // error_log('Content Craft AI: Nonce verification failed');
        return false;
    }

    // Always return true to allow auth process to happen
    // Actual auth happens inside the endpoints
    return true;
}

/**
 * Register authentication routes
 */
function content_craft_ai_register_auth_routes()
{
    // Login route
    register_rest_route('content-craft-ai/v1', '/auth/login', array(
        'methods' => 'POST',
        'callback' => 'content_craft_ai_handle_login',
        'permission_callback' => 'content_craft_ai_permission_callback',
    ));

    // Registration route
    register_rest_route('content-craft-ai/v1', '/auth/register', array(
        'methods' => 'POST',
        'callback' => 'content_craft_ai_handle_register',
        'permission_callback' => 'content_craft_ai_permission_callback',
    ));

    // Forgot password route
    register_rest_route('content-craft-ai/v1', '/auth/forgot-password', array(
        'methods' => 'POST',
        'callback' => 'content_craft_ai_handle_forgot_password',
        'permission_callback' => 'content_craft_ai_permission_callback',
    ));

    // Reset password route
    register_rest_route('content-craft-ai/v1', '/auth/reset-password', array(
        'methods' => 'POST',
        'callback' => 'content_craft_ai_handle_reset_password',
        'permission_callback' => 'content_craft_ai_permission_callback',
    ));

    // Logout route
    register_rest_route('content-craft-ai/v1', '/auth/logout', array(
        'methods' => 'POST',
        'callback' => 'content_craft_ai_handle_logout',
        'permission_callback' => 'content_craft_ai_permission_callback',
    ));

    // Verify token and get user data - This always calls external API
    register_rest_route('content-craft-ai/v1', '/auth/me', array(
        'methods' => 'GET',
        'callback' => 'content_craft_ai_handle_me',
        'permission_callback' => 'content_craft_ai_permission_callback',
    ));
}

// Register routes
add_action('rest_api_init', 'content_craft_ai_register_auth_routes');
