<?php

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

final class Aysa_AI_Visibility_Ajax_Controller {
    private $client;

    public function __construct(Aysa_AI_Visibility_API_Client $client) {
        $this->client = $client;
    }

    public function register() {
        add_action('wp_ajax_aysa_ai_visibility_status', array($this, 'status'));
        add_action('wp_ajax_aysa_ai_visibility_request', array($this, 'request'));
    }

    public function status() {
        $this->dispatch('/v1/ai-visibility/status', array());
    }

    public function request() {
        if (!current_user_can('manage_options')) {
            wp_send_json_error(array('error' => 'forbidden'), 403);
        }
        if (!check_ajax_referer('aysa_ai_visibility', 'nonce', false)) {
            wp_send_json_error(array('error' => 'nonce_invalid'), 403);
        }
        $operation = isset($_POST['operation']) ? sanitize_key(wp_unslash($_POST['operation'])) : '';
        $routes = array(
            'setup_preview' => '/v1/ai-visibility/setup/preview',
            'setup_read' => '/v1/ai-visibility/setup/read',
            'profile_save' => '/v1/ai-visibility/setup/profile/save',
            'entities_list' => '/v1/ai-visibility/setup/entities/list',
            'entity_save' => '/v1/ai-visibility/setup/entities/save',
            'entity_archive' => '/v1/ai-visibility/setup/entities/archive',
            'entity_restore' => '/v1/ai-visibility/setup/entities/restore',
            'estimate' => '/v1/ai-visibility/estimate',
            'overview_read' => '/v1/ai-visibility/overview/read',
            'runs_list' => '/v1/ai-visibility/runs/list',
            'evidence_read' => '/v1/ai-visibility/evidence/read',
            'trends_read' => '/v1/ai-visibility/trends/read',
            'signals_read' => '/v1/ai-visibility/signals/read',
            'content_analyze' => '/v1/ai-visibility/content-analyzer/analyze',
            'content_analyzer_select' => '/v1/ai-visibility/content-analyzer/select',
            'commerce_analyze' => '/v1/ai-visibility/commerce/analyze',
            'correlation_read' => '/v1/ai-visibility/correlation/read',
            'knowledge_sources_list' => '/v1/ai-visibility/knowledge-base/sources/list',
            'knowledge_wordpress_sync' => '/v1/ai-visibility/knowledge-base/sources/import',
            'knowledge_source_archive' => '/v1/ai-visibility/knowledge-base/sources/archive',
            'knowledge_source_restore' => '/v1/ai-visibility/knowledge-base/sources/restore',
            'export_read' => '/v1/ai-visibility/exports/read',
            'run_quote' => '/v1/ai-visibility/runs/quote',
            'run_policy_prepare' => '/v1/ai-visibility/runs/policy/prepare',
            'run_policy_confirm' => '/v1/ai-visibility/runs/policy/confirm',
            'run_start' => '/v1/ai-visibility/runs/start',
            'run_cancel' => '/v1/ai-visibility/runs/cancel',
            'run_retry_prepare' => '/v1/ai-visibility/runs/retry/prepare',
            'run_retry' => '/v1/ai-visibility/runs/retry',
            'run_reprocess_prepare' => '/v1/ai-visibility/runs/reprocess/prepare',
            'run_reprocess_start' => '/v1/ai-visibility/runs/reprocess/start',
            'schedule_prepare' => '/v1/ai-visibility/runs/schedule/prepare',
            'schedule_confirm' => '/v1/ai-visibility/runs/schedule/confirm',
            'schedule_status' => '/v1/ai-visibility/runs/schedule/status',
            'schedule_disable' => '/v1/ai-visibility/runs/schedule/disable',
            'insights_list' => '/v1/ai-visibility/insights/list',
            'insight_status' => '/v1/ai-visibility/insights/status',
            'action_plan_build' => '/v1/ai-visibility/action-plan/build',
            'action_plan_read' => '/v1/ai-visibility/action-plan/read',
            'action_plan_approval_prepare' => '/v1/ai-visibility/action-plan/approval/prepare',
            'action_plan_approval_confirm' => '/v1/ai-visibility/action-plan/approval/confirm',
            'action_plan_proposals_dispatch' => '/v1/ai-visibility/action-plan/proposals/dispatch',
            'interventions_read' => '/v1/ai-visibility/interventions/read',
            'impact_assess' => '/v1/ai-visibility/impact/assess',
        );
        if (!isset($routes[$operation])) {
            wp_send_json_error(array('error' => 'operation_invalid'), 400);
        }
        // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- Structured JSON is decoded and each operation validates its own typed fields.
        $raw = isset($_POST['payload']) ? (string) wp_unslash($_POST['payload']) : '{}';
        $payload = json_decode($raw, true);
        if (!is_array($payload)) {
            wp_send_json_error(array('error' => 'payload_invalid'), 400);
        }
        if ($operation === 'commerce_analyze') {
            $snapshot = Aysa_AI_Visibility_Commerce_Snapshot::build();
            if (is_wp_error($snapshot)) {
                wp_send_json_error(array(
                    'error' => sanitize_key($snapshot->get_error_code()),
                    'message' => $snapshot->get_error_message(),
                ), 409);
            }
            $payload['catalog'] = $snapshot['catalog'];
            $payload['readiness_context'] = $snapshot['readiness_context'];
        }
        if ($operation === 'knowledge_wordpress_sync') {
            $snapshot = Aysa_AI_Visibility_Knowledge_Snapshot::build();
            if (is_wp_error($snapshot)) {
                wp_send_json_error(array(
                    'error' => sanitize_key($snapshot->get_error_code()),
                    'message' => $snapshot->get_error_message(),
                ), 409);
            }
            $payload['source'] = $snapshot;
        }
        $this->dispatch($routes[$operation], $payload);
    }

    private function dispatch($path, $payload) {
        if (!current_user_can('manage_options')) {
            wp_send_json_error(array('error' => 'forbidden'), 403);
        }
        if (!check_ajax_referer('aysa_ai_visibility', 'nonce', false)) {
            wp_send_json_error(array('error' => 'nonce_invalid'), 403);
        }
        $result = $this->client->request($path, $payload);
        if (is_wp_error($result)) {
            $data = $result->get_error_data();
            $status = is_array($data) ? absint($data['status'] ?? 500) : 500;
            wp_send_json_error(array(
                'error' => sanitize_key($result->get_error_code()),
                'message' => $result->get_error_message(),
            ), $status >= 400 && $status <= 599 ? $status : 500);
        }
        wp_send_json_success($result);
    }
}
