<?php

namespace PloverCRM\Core\Api\V1;

use PloverCRM\Core\Api\AbstractEndpoint;
use WP_REST_Request;

/**
 * Web Push Endpoint
 * 
 * GET    /wp-json/plover-crm/v1/push/vapid-key   - Get VAPID public key
 * POST   /wp-json/plover-crm/v1/push/subscribe    - Subscribe to web push
 * DELETE /wp-json/plover-crm/v1/push/subscribe    - Unsubscribe from web push
 */
class WebPushEndpoint extends AbstractEndpoint
{
  private const VAPID_OPTION_KEY = 'plover_crm_vapid_keys';

  public function getRoute(): string
  {
    return '/push/(?P<action>[a-z-]+)';
  }

  public function getMethod()
  {
    return ['GET', 'POST', 'DELETE'];
  }

  public function handle(WP_REST_Request $request)
  {
    $action = $request->get_param('action');

    return match ($action) {
      'vapid-key' => $this->getVapidKey(),
      'subscribe' => $request->get_method() === 'DELETE'
        ? $this->unsubscribe($request)
        : $this->subscribe($request),
      default => $this->error('Unknown action', 404),
    };
  }

  /**
   * Return the VAPID public key for browser subscription
   */
  private function getVapidKey()
  {
    $vapid = get_option(self::VAPID_OPTION_KEY);

    if (!$vapid || empty($vapid['publicKey'])) {
      return $this->error('VAPID keys not configured. Please deactivate and reactivate the plugin.', 500);
    }

    return $this->success([
      'publicKey' => $vapid['publicKey'],
    ]);
  }

  /**
   * Store a web push subscription
   */
  private function subscribe(WP_REST_Request $request)
  {
    $data = $request->get_json_params();

    $endpoint = $data['endpoint'] ?? '';
    $p256dh = $data['keys']['p256dh'] ?? '';
    $auth = $data['keys']['auth'] ?? '';

    if (!$endpoint || !$p256dh || !$auth) {
      return $this->error('Missing subscription data (endpoint, keys.p256dh, keys.auth required)', 422);
    }

    $user_id = get_current_user_id();

    if (!$user_id) {
      return $this->error('Not authenticated', 401);
    }

    global $wpdb;
    $table = $wpdb->prefix . 'plover_crm_web_push_subscriptions';

    // Check if this endpoint already exists for this user
    $existing = $wpdb->get_var($wpdb->prepare(
      "SELECT id FROM $table WHERE user_id = %d AND endpoint = %s LIMIT 1",
      $user_id,
      $endpoint
    ));

    if ($existing) {
      // Update keys (they can rotate)
      $wpdb->update(
        $table,
        [
          'p256dh' => $p256dh,
          'auth' => $auth,
        ],
        ['id' => $existing],
        ['%s', '%s'],
        ['%d']
      );
    } else {
      $wpdb->insert(
        $table,
        [
          'user_id' => $user_id,
          'endpoint' => $endpoint,
          'p256dh' => $p256dh,
          'auth' => $auth,
        ],
        ['%d', '%s', '%s', '%s']
      );
    }

    return $this->success(['subscribed' => true]);
  }

  /**
   * Remove a web push subscription
   */
  private function unsubscribe(WP_REST_Request $request)
  {
    $data = $request->get_json_params();
    $endpoint = $data['endpoint'] ?? '';

    if (!$endpoint) {
      return $this->error('Missing endpoint', 422);
    }

    $user_id = get_current_user_id();

    global $wpdb;
    $table = $wpdb->prefix . 'plover_crm_web_push_subscriptions';

    $wpdb->delete(
      $table,
      [
        'user_id' => $user_id,
        'endpoint' => $endpoint,
      ],
      ['%d', '%s']
    );

    return $this->success(['unsubscribed' => true]);
  }
}
