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';

export default createEdgeFunction(
  {
    name: 'trigger-notification',
    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 { workflowId, subscriberId, topicKey, payload, overrides } = await req.json() as {
      workflowId: string;
      subscriberId?: string;
      topicKey?: string;
      payload: Record<string, unknown>;
      overrides?: Record<string, unknown>;
    };

    // Support both individual subscribers and topics
    if (!subscriberId && !topicKey) {
      throw new Error('Either subscriberId or topicKey must be provided');
    }

    const recipient = subscriberId 
      ? { subscriberId }
      : { topicKey: topicKey! };

    context.span.setAttribute('action', 'trigger_notification');
    edgeLogger.info('Triggering notification', { 
      workflowId, 
      recipient, 
      requestId: context.requestId,
      action: 'trigger_notification'
    });

    const result = await novu.trigger({
      to: recipient,
      workflowId,
      payload,
      overrides,
    });

    edgeLogger.info('Notification triggered successfully', { 
      requestId: context.requestId,
      transactionId: result.data.transactionId
    });

    return new Response(
      JSON.stringify({
        success: true,
        transactionId: result.data.transactionId,
      }),
      {
        headers: { 
          'Content-Type': 'application/json',
        },
        status: 200,
      }
    );
  }
);
