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: 'update-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, email, firstName, lastName, phone, avatar, data } = await req.json() as {
      subscriberId: string;
      email?: string;
      firstName?: string;
      lastName?: string;
      phone?: string;
      avatar?: string;
      data?: Record<string, unknown>;
    };

    context.span.setAttribute('action', 'update_novu_subscriber');
    edgeLogger.info('Updating Novu subscriber', { action: 'update_novu_subscriber', subscriberId, email, firstName, requestId: context.requestId });

    const subscriber = await novu.subscribers.update(subscriberId, {
      email,
      firstName,
      lastName,
      phone,
      avatar,
      data,
    });

    edgeLogger.info('Subscriber updated successfully', { action: 'update_novu_subscriber', subscriberId: subscriber.data._id, requestId: context.requestId });

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