import { Novu } from "npm:@novu/api@1.6.0";
import { corsHeaders } from '../_shared/cors.ts';
import { edgeLogger } from "../_shared/logger.ts";
import { createEdgeFunction } from '../_shared/edgeFunctionWrapper.ts';
import { validateString } from '../_shared/typeValidation.ts';

export default createEdgeFunction(
  {
    name: 'remove-novu-subscriber',
    requireAuth: false,
    corsHeaders: corsHeaders
  },
  async (req, context) => {
    const novuApiKey = Deno.env.get('NOVU_API_KEY');
    
    if (!novuApiKey) {
      throw new Error('NOVU_API_KEY is not configured');
    }

    const novu = new Novu({ 
      secretKey: novuApiKey 
    });

    const { subscriberId, deleteSubscriber = false } = await req.json() as {
      subscriberId: string;
      deleteSubscriber?: boolean;
    };

    validateString(subscriberId, 'subscriberId', { requestId: context.requestId });

    context.span.setAttribute('action', 'remove_novu_subscriber');
    edgeLogger.info('Removing subscriber from users topic', { action: 'remove_novu_subscriber', subscriberId, requestId: context.requestId });

    // Remove subscriber from "users" topic
    try {
      await novu.topics.removeSubscribers('users', {
        subscribers: [subscriberId],
      });
      edgeLogger.info('Successfully removed subscriber from users topic', { action: 'remove_novu_subscriber', subscriberId, requestId: context.requestId });
    } catch (topicError: any) {
      edgeLogger.error('Failed to remove subscriber from users topic', { action: 'remove_novu_subscriber', subscriberId, error: topicError.message, requestId: context.requestId });
      // Continue - we still want to delete the subscriber if requested
    }

    // Optionally delete the subscriber entirely from Novu
    if (deleteSubscriber) {
      try {
        edgeLogger.info('Deleting subscriber from Novu', { action: 'remove_novu_subscriber', subscriberId, requestId: context.requestId });
        await novu.subscribers.delete(subscriberId);
        edgeLogger.info('Successfully deleted subscriber from Novu', { action: 'remove_novu_subscriber', subscriberId, requestId: context.requestId });
      } catch (deleteError: any) {
        edgeLogger.error('Failed to delete subscriber from Novu', { action: 'remove_novu_subscriber', subscriberId, error: deleteError.message, requestId: context.requestId });
        throw deleteError;
      }
    }

    return new Response(
      JSON.stringify({
        success: true,
        subscriberId,
        removedFromTopic: true,
        deleted: deleteSubscriber,
      }),
      {
        headers: { 
          'Content-Type': 'application/json',
        },
        status: 200,
      }
    );
  }
);
