<?php

namespace Datalumo\Admin;

use Datalumo\PhpSdk\Exceptions\DatalumoException;
use Datalumo\Sync\BulkSync;

class AjaxHandler
{
    public function __construct()
    {
        add_action('wp_ajax_datalumo_test_connection', [$this, 'testConnection']);
        add_action('wp_ajax_datalumo_save_api_key', [$this, 'saveApiKey']);
        add_action('wp_ajax_datalumo_fetch_collections', [$this, 'fetchCollections']);
        add_action('wp_ajax_datalumo_fetch_integrations', [$this, 'fetchIntegrations']);
        add_action('wp_ajax_datalumo_create_collection', [$this, 'createCollection']);
        add_action('wp_ajax_datalumo_create_integration', [$this, 'createIntegration']);
        add_action('wp_ajax_datalumo_trigger_sync', [$this, 'triggerSync']);
        add_action('wp_ajax_datalumo_cancel_sync', [$this, 'cancelSync']);
        add_action('wp_ajax_datalumo_sync_status', [$this, 'syncStatus']);
        add_action('wp_ajax_datalumo_delete_content_sync', [$this, 'deleteContentSync']);
    }

    private function verifyRequest(): void
    {
        if (! check_ajax_referer('datalumo_admin', 'nonce', false)) {
            wp_send_json_error(['message' => __('Invalid security token.', 'datalumo')], 403);
        }

        if (! current_user_can('manage_options')) {
            wp_send_json_error(['message' => __('Insufficient permissions.', 'datalumo')], 403);
        }
    }

    public function testConnection(): void
    {
        $this->verifyRequest();

        $apiKey = sanitize_text_field(wp_unslash($_POST['api_key'] ?? ''));

        if (empty($apiKey)) {
            wp_send_json_error(['message' => __('API Key is required.', 'datalumo')]);
        }

        try {
            $sdk = datalumo_sdk($apiKey);
            $sdk->collections()->list();
        } catch (DatalumoException $e) {
            wp_send_json_error(['message' => $e->getMessage()]);
        }

        wp_send_json_success(['message' => __('Connection successful!', 'datalumo')]);
    }

    public function saveApiKey(): void
    {
        $this->verifyRequest();

        $apiKey = sanitize_text_field(wp_unslash($_POST['api_key'] ?? ''));

        if (empty($apiKey)) {
            wp_send_json_error(['message' => __('API Key is required.', 'datalumo')]);
        }

        // Test the key first
        try {
            $sdk = datalumo_sdk($apiKey);
            $sdk->collections()->list();
        } catch (DatalumoException $e) {
            wp_send_json_error(['message' => $e->getMessage()]);
        }

        // Key is valid, save it
        update_option('datalumo_api_key', $apiKey);

        wp_send_json_success(['message' => __('Connection successful! API key saved.', 'datalumo')]);
    }

    public function fetchCollections(): void
    {
        $this->verifyRequest();

        try {
            $sdk = datalumo_sdk();
            $result = $sdk->collections()->list();
        } catch (DatalumoException $e) {
            wp_send_json_error(['message' => $e->getMessage()]);
        }

        $collections = array_map(function ($collection) {
            return [
                'id'   => $collection->id,
                'name' => $collection->name,
            ];
        }, $result->data);

        wp_send_json_success(['collections' => $collections]);
    }

    public function createCollection(): void
    {
        $this->verifyRequest();

        $name = sanitize_text_field(wp_unslash($_POST['name'] ?? ''));

        if (empty($name)) {
            wp_send_json_error(['message' => __('Collection name is required.', 'datalumo')]);
        }

        try {
            $sdk = datalumo_sdk();
            $collection = $sdk->collections()->create($name);
        } catch (DatalumoException $e) {
            wp_send_json_error(['message' => $e->getMessage()]);
        }

        wp_send_json_success([
            'collection' => [
                'id'   => $collection->id,
                'name' => $collection->name,
            ],
        ]);
    }

    public function fetchIntegrations(): void
    {
        $this->verifyRequest();

        $type = sanitize_text_field(wp_unslash($_POST['type'] ?? ''));

        try {
            $sdk = datalumo_sdk();
            $result = $sdk->integrations()->list($type ?: null);
        } catch (DatalumoException $e) {
            wp_send_json_error(['message' => $e->getMessage()]);
        }

        $integrations = [];

        foreach ($result->data as $integration) {
            if ($integration->isActive) {
                $integrations[] = [
                    'id'   => $integration->id,
                    'name' => $integration->name,
                ];
            }
        }

        wp_send_json_success(['integrations' => $integrations]);
    }

    public function createIntegration(): void
    {
        $this->verifyRequest();

        $name = sanitize_text_field(wp_unslash($_POST['name'] ?? ''));
        $type = sanitize_text_field(wp_unslash($_POST['type'] ?? ''));
        $collectionIds = array_filter(array_map('sanitize_text_field', wp_unslash((array) ($_POST['collection_ids'] ?? []))));

        if (empty($name)) {
            wp_send_json_error(['message' => __('Integration name is required.', 'datalumo')]);
        }

        if (empty($type)) {
            wp_send_json_error(['message' => __('Integration type is required.', 'datalumo')]);
        }

        if (empty($collectionIds)) {
            wp_send_json_error(['message' => __('At least one collection is required.', 'datalumo')]);
        }

        $domain = wp_parse_url(home_url(), PHP_URL_HOST);

        $data = [
            'name'           => $name,
            'type'           => $type,
            'collection_ids' => array_values($collectionIds),
            'label'          => "WordPress search integration",
        ];

        if ($domain) {
            $data['allowed_domains'] = [$domain];
            $data['label']           = "WordPress search integration for {$domain}";
        }

        try {
            $sdk = datalumo_sdk();
            $integration = $sdk->integrations()->create($data);
        } catch (DatalumoException $e) {
            wp_send_json_error(['message' => $e->getMessage()]);
        }

        wp_send_json_success([
            'integration' => [
                'id'   => $integration->id,
                'name' => $integration->name,
            ],
        ]);
    }

    public function triggerSync(): void
    {
        $this->verifyRequest();

        $syncId = sanitize_text_field(wp_unslash($_POST['sync_id'] ?? ''));

        if (empty($syncId)) {
            wp_send_json_error(['message' => __('Sync ID is required.', 'datalumo')]);
        }

        $sync = datalumo_get_content_sync($syncId);

        if (! $sync) {
            wp_send_json_error(['message' => __('Content sync not found.', 'datalumo')]);
        }

        $bulkSync = new BulkSync();

        if ($bulkSync->isInProgress($syncId)) {
            wp_send_json_error(['message' => __('A sync is already in progress.', 'datalumo')]);
        }

        $bulkSync->start($syncId);

        wp_send_json_success(['message' => __('Bulk sync started.', 'datalumo')]);
    }

    public function cancelSync(): void
    {
        $this->verifyRequest();

        $syncId = sanitize_text_field(wp_unslash($_POST['sync_id'] ?? ''));

        if (empty($syncId)) {
            wp_send_json_error(['message' => __('Sync ID is required.', 'datalumo')]);
        }

        $bulkSync = new BulkSync();
        $cancelled = $bulkSync->cancel($syncId);

        wp_send_json_success([
            'message'   => __('Sync cancelled.', 'datalumo'),
            'cancelled' => $cancelled,
        ]);
    }

    public function syncStatus(): void
    {
        $this->verifyRequest();

        $syncId = sanitize_text_field(wp_unslash($_POST['sync_id'] ?? ''));

        if (empty($syncId)) {
            wp_send_json_error(['message' => __('Sync ID is required.', 'datalumo')]);
        }

        $bulkSync = new BulkSync();

        wp_send_json_success($bulkSync->getStatus($syncId));
    }

    public function deleteContentSync(): void
    {
        $this->verifyRequest();

        $syncId = sanitize_text_field(wp_unslash($_POST['sync_id'] ?? ''));

        if (empty($syncId)) {
            wp_send_json_error(['message' => __('Sync ID is required.', 'datalumo')]);
        }

        $sync = datalumo_get_content_sync($syncId);

        if (! $sync) {
            wp_send_json_error(['message' => __('Content sync not found.', 'datalumo')]);
        }

        // Schedule deletion of entries from Datalumo
        $bulkSync = new BulkSync();
        $bulkSync->deleteEntries($syncId);

        // Remove sync config
        $syncs = datalumo_get_content_syncs();
        $syncs = array_values(array_filter($syncs, fn($s) => $s['id'] !== $syncId));
        update_option('datalumo_content_syncs', $syncs);

        // Remove sync state (new per-sync option and legacy shared option)
        delete_option('datalumo_sync_state_' . $syncId);

        $states = datalumo_get_sync_states();
        // Also clean up legacy shared option if it exists
        $legacyStates = get_option('datalumo_sync_states', []);

        if (is_array($legacyStates) && isset($legacyStates[$syncId])) {
            unset($legacyStates[$syncId]);
            update_option('datalumo_sync_states', $legacyStates);
        }

        wp_send_json_success(['message' => __('Content sync deleted.', 'datalumo')]);
    }
}
