import { serve } from "https://deno.land/std@0.190.0/http/server.ts";
import { Novu } from "npm:@novu/api@1.6.0";
import { startRequest, endRequest } from "../_shared/logger.ts";

const corsHeaders = {
  'Access-Control-Allow-Origin': '*',
  'Access-Control-Allow-Headers': 'authorization, x-client-info, apikey, content-type, x-request-id',
};

serve(async (req) => {
  if (req.method === 'OPTIONS') {
    return new Response(null, { headers: corsHeaders });
  }

  const tracking = startRequest('remove-novu-subscriber');

  try {
    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;
    };

    if (!subscriberId || typeof subscriberId !== 'string' || subscriberId.trim() === '') {
      return new Response(
        JSON.stringify({
          success: false,
          error: 'subscriberId is required and must be a non-empty string',
        }),
        {
          headers: { ...corsHeaders, 'Content-Type': 'application/json' },
          status: 400,
        }
      );
    }

    console.log('Removing subscriber from "users" topic:', { subscriberId, requestId: tracking.requestId });

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

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

    endRequest(tracking, 200);

    return new Response(
      JSON.stringify({
        success: true,
        subscriberId,
        removedFromTopic: true,
        deleted: deleteSubscriber,
        requestId: tracking.requestId
      }),
      {
        headers: { 
          ...corsHeaders, 
          'Content-Type': 'application/json',
          'X-Request-ID': tracking.requestId
        },
        status: 200,
      }
    );
  } catch (error: unknown) {
    const errorMessage = error instanceof Error ? error.message : 'Unknown error occurred';
    console.error('Error removing Novu subscriber:', errorMessage, { requestId: tracking.requestId });
    
    endRequest(tracking, 500, errorMessage);

    return new Response(
      JSON.stringify({
        success: false,
        error: errorMessage,
        requestId: tracking.requestId
      }),
      {
        headers: { 
          ...corsHeaders, 
          'Content-Type': 'application/json',
          'X-Request-ID': tracking.requestId
        },
        status: 500,
      }
    );
  }
});
