<?php

declare(strict_types=1);

namespace PloverCRM\Modules\Integrations\Endpoints;

use WP_REST_Request;
use PloverCRM\Core\Api\AbstractEndpoint;
use PloverCRM\Modules\Integrations\Services\MetaConnectionService;
use PloverCRM\Modules\Integrations\Services\MetaApiService;

/**
 * Meta Connections REST API Endpoint
 * 
 * Handles CRUD operations for Meta/Facebook page connections.
 */
class MetaConnectionsEndpoint extends AbstractEndpoint
{
    /**
     * Get endpoint route (base route, we register multiple in register())
     */
    public function getRoute(): string
    {
        return '/meta/connections';
    }

    /**
     * Get HTTP method (not used since we override register)
     */
    public function getMethod(): string
    {
        return 'GET';
    }

    public function checkPermission(WP_REST_Request $request)
    {
        return $this->checkAuthenticatedCapability($request, 'manage_options');
    }

    /**
     * Register routes
     * 
     * @param string $namespace
     */
    public function register(string $namespace): void
    {
        // List connections
        register_rest_route($namespace, '/meta/connections', [
            'methods' => 'GET',
            'callback' => [$this, 'listConnections'],
            'permission_callback' => [$this, 'checkPermission'],
        ]);

        // Create connection
        register_rest_route($namespace, '/meta/connections', [
            'methods' => 'POST',
            'callback' => [$this, 'createConnection'],
            'permission_callback' => [$this, 'checkPermission'],
        ]);

        // Delete connection
        register_rest_route($namespace, '/meta/connections/(?P<id>\d+)', [
            'methods' => 'DELETE',
            'callback' => [$this, 'deleteConnection'],
            'permission_callback' => [$this, 'checkPermission'],
        ]);

        // Test connection
        register_rest_route($namespace, '/meta/connections/(?P<id>\d+)/test', [
            'methods' => 'POST',
            'callback' => [$this, 'testConnection'],
            'permission_callback' => [$this, 'checkPermission'],
        ]);
    }

    /**
     * GET /meta/connections - List all connections
     */
    public function listConnections(WP_REST_Request $request)
    {
        $connections = MetaConnectionService::getAll();

        return $this->success([
            'connections' => array_map(fn($c) => $c->toArray(), $connections),
        ]);
    }

    /**
     * POST /meta/connections - Create new connection
     */
    public function createConnection(WP_REST_Request $request)
    {
        $pageId = sanitize_text_field($request->get_param('page_id') ?? '');
        $pageName = sanitize_text_field($request->get_param('page_name') ?? '');
        $pageToken = sanitize_text_field($request->get_param('page_access_token') ?? '');

        // Validate
        if (empty($pageId) || empty($pageToken)) {
            return $this->error('Page ID and access token are required', 400);
        }

        // Check for duplicates
        if (MetaConnectionService::exists($pageId)) {
            return $this->error('This page is already connected', 409);
        }

        // Create connection
        $connectionId = MetaConnectionService::create([
            'page_id' => $pageId,
            'page_name' => $pageName,
            'page_access_token' => $pageToken,
            'status' => 'active',
        ]);

        if (!$connectionId) {
            return $this->error('Failed to save connection', 500);
        }

        $connection = MetaConnectionService::getById($connectionId);
        $api = new MetaApiService();

        // Subscribe to webhooks
        $subscribed = $api->subscribePage($connection);

        // Register with central server
        $registered = MetaConnectionService::registerWithCentral($pageId, home_url());

        // Determine final status
        $status = ($subscribed && $registered) ? 'active' : 'pending';
        if ($status === 'pending') {
            MetaConnectionService::update($connectionId, ['status' => 'pending']);
        }

        return $this->success([
            'id' => $connectionId,
            'page_name' => $pageName,
            'status' => $status,
            'webhook_subscribed' => $subscribed,
            'central_registered' => $registered,
        ], [], 201);
    }

    /**
     * DELETE /meta/connections/{id} - Delete connection
     */
    public function deleteConnection(WP_REST_Request $request)
    {
        $id = (int) $request->get_param('id');

        $connection = MetaConnectionService::getById($id);
        if (!$connection) {
            return $this->error('Connection not found', 404);
        }

        // Clear cache
        $api = new MetaApiService();
        $api->clearCache();

        // Delete (this also unregisters from central)
        if (!MetaConnectionService::delete($id)) {
            return $this->error('Failed to disconnect', 500);
        }

        return $this->success([
            'message' => 'Page disconnected successfully',
            'page_name' => $connection->pageName,
        ]);
    }

    /**
     * POST /meta/connections/{id}/test - Test connection
     */
    public function testConnection(WP_REST_Request $request)
    {
        $id = (int) $request->get_param('id');

        $connection = MetaConnectionService::getById($id);
        if (!$connection) {
            return $this->error('Connection not found', 404);
        }

        $api = new MetaApiService();
        $result = $api->testConnection($connection);

        return $this->success($result);
    }

    /**
     * Handle method - not used (we have specific handlers)
     */
    public function handle(WP_REST_Request $request)
    {
        // This method is required by AbstractEndpoint but not used
        // since we register specific routes in register()
        return $this->error('Method not implemented', 501);
    }
}
