<?php

namespace PloverCRM\Modules\Integrations\Services;

/**
 * Token Management Service
 * 
 * Handles token validation for Meta connections.
 * 
 * Note: Page access tokens obtained using a long-lived user token NEVER expire.
 * No refresh mechanism is needed. Tokens only become invalid if:
 * - User changes their Facebook password
 * - User revokes app permissions
 * - User is no longer admin of the page
 * 
 * See: https://developers.facebook.com/docs/pages/access-tokens
 */
class TokenManagementService
{
  /**
   * Test a specific connection by making an API call
   */
  public static function testConnection(int $connectionId): array
  {
    $connection = MetaConnectionService::getById($connectionId);

    if (!$connection) {
      return [
        'valid' => false,
        'error' => 'Connection not found',
      ];
    }

    if (empty($connection->pageAccessToken)) {
      return [
        'valid' => false,
        'error' => 'No access token configured',
      ];
    }

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

    // Map 'success' to 'valid' for consistency
    return [
      'valid' => $result['success'] ?? false,
      'error' => $result['error'] ?? null,
      'page_name' => $result['page_name'] ?? $connection->pageName,
    ];
  }

  /**
   * Test all active connections
   * 
   * @return array Results for each connection
   */
  public static function testAllConnections(): array
  {
    $connections = MetaConnectionService::getAll(true);
    $results = [];

    foreach ($connections as $connection) {
      $results[$connection->id] = self::testConnection($connection->id);
    }

    return $results;
  }

  /**
   * Get summary of all connections' status
   */
  public static function getConnectionsSummary(): array
  {
    $connections = MetaConnectionService::getAll(false);

    $summary = [
      'total' => count($connections),
      'active' => 0,
      'inactive' => 0,
      'connections' => [],
    ];

    foreach ($connections as $connection) {
      if ($connection->isActive()) {
        $summary['active']++;
      } else {
        $summary['inactive']++;
      }

      $summary['connections'][] = [
        'id' => $connection->id,
        'page_name' => $connection->pageName,
        'page_id' => $connection->pageId,
        'status' => $connection->status,
        'connected_at' => $connection->connectedAt,
      ];
    }

    return $summary;
  }
}
