<?php
declare(strict_types=1);
// ==================================================
// Nuclear Fancy Pants Edition™ — NUCLEAR+++
// File: wp-content/plugins/automarketer-ai/src/Controllers/AiProviderController.php
// Last Edited: January 03, 2026
// Description: Nuclear-grade REST controller for AI provider config — configure (provider/key/model), test connection + models fetch, get current config (masked) — custom capability, nonce-protected, JSON responses — NUCLEAR+++
// ==================================================

namespace AutoMarketerAI\Controllers;

use AutoMarketerAI\Services\AiProviderService;
use WP_Error;
use WP_REST_Controller;
use WP_REST_Request;
use WP_REST_Response;
use WP_REST_Server;

final class AiProviderController extends WP_REST_Controller
{
    protected string $namespace = 'automarketer-ai/v1';
    protected string $rest_base = 'ai-provider';

    public function register_routes(): void
    {
        register_rest_route($this->namespace, '/' . $this->rest_base . '/configure', [
            [
                'methods'             => WP_REST_Server::CREATABLE,
                'callback'            => [$this, 'configure'],
                'permission_callback' => [$this, 'permission_check'],
                'args'                => [
                    'provider' => [
                        'required'          => true,
                        'sanitize_callback' => 'sanitize_text_field',
                    ],
                    'api_key'  => [
                        'sanitize_callback' => 'sanitize_text_field',
                    ],
                    'model'    => [
                        'sanitize_callback' => 'sanitize_text_field',
                    ],
                ],
            ],
        ]);

        register_rest_route($this->namespace, '/' . $this->rest_base . '/test', [
            [
                'methods'             => WP_REST_Server::CREATABLE,
                'callback'            => [$this, 'test'],
                'permission_callback' => [$this, 'permission_check'],
                'args'                => [
                    'provider' => [
                        'sanitize_callback' => 'sanitize_text_field',
                    ],
                ],
            ],
        ]);

        register_rest_route($this->namespace, '/' . $this->rest_base . '/config', [
            [
                'methods'             => WP_REST_Server::READABLE,
                'callback'            => [$this, 'get_config'],
                'permission_callback' => [$this, 'permission_check'],
            ],
        ]);
    }

    public function permission_check(WP_REST_Request $request): bool
    {
        return current_user_can('manage_automarketer_ai');
    }

    public function configure(WP_REST_Request $request): WP_REST_Response
    {
        $provider = $request['provider'];
        if (!array_key_exists($provider, AiProviderService::PROVIDERS)) {
            return new WP_REST_Response(['success' => false, 'message' => 'Invalid provider'], 400);
        }

        AiProviderService::setSelectedProvider($provider);

        if ($model = $request->get_param('model')) {
            AiProviderService::setSelectedModel($model);
        }

        if ($api_key = $request->get_param('api_key')) {
            AiProviderService::addOrUpdateKey($provider, $api_key);
        }

        return new WP_REST_Response([
            'success' => true,
            'message' => 'Configuration saved',
            'config'  => AiProviderService::getConfig(),
        ], 200);
    }

    public function test(WP_REST_Request $request): WP_REST_Response
    {
        $provider = $request->get_param('provider') ?: AiProviderService::getSelectedProvider();

        // Temporarily switch to test provider if different
        $original = AiProviderService::getSelectedProvider();
        AiProviderService::setSelectedProvider($provider);

        try {
            $service = new AiProviderService();
            $result  = $service->testConnection();
        } catch (\Exception $e) {
            AiProviderService::setSelectedProvider($original);
            return new WP_REST_Response([
                'success' => false,
                'message' => $e->getMessage(),
            ], 400);
        }

        AiProviderService::setSelectedProvider($original);

        if (is_wp_error($result)) {
            return new WP_REST_Response([
                'success' => false,
                'message' => $result->get_error_message(),
            ], 400);
        }

        return new WP_REST_Response([
            'success' => true,
            'models'  => $result['models'],
            'timestamp' => $result['timestamp'],
        ], 200);
    }

    public function get_config(WP_REST_Request $request): WP_REST_Response
    {
        return new WP_REST_Response([
            'success' => true,
            'config'  => AiProviderService::getConfig(),
        ], 200);
    }
}