import { createClient } from 'https://esm.sh/@supabase/supabase-js@2';
import { createEdgeFunction } from '../_shared/edgeFunctionWrapper.ts';
import { edgeLogger } from '../_shared/logger.ts';

export default createEdgeFunction(
  {
    name: 'process-scheduled-deletions',
    requireAuth: false,
  },
  async (req, context, supabase) => {
    edgeLogger.info('Processing scheduled account deletions', { 
      requestId: context.requestId 
    });

    // Find confirmed deletion requests that are past their scheduled date
    const { data: pendingDeletions, error: fetchError } = await supabase
      .from('account_deletion_requests')
      .select('*')
      .eq('status', 'confirmed')
      .lt('scheduled_deletion_at', new Date().toISOString());

    if (fetchError) {
      throw fetchError;
    }

    if (!pendingDeletions || pendingDeletions.length === 0) {
      edgeLogger.info('No deletions to process', { 
        requestId: context.requestId 
      });
      
      return new Response(
        JSON.stringify({
          success: true,
          message: 'No deletions to process',
          processed: 0,
        }),
        { headers: { 'Content-Type': 'application/json' } }
      );
    }

    edgeLogger.info('Found deletions to process', { 
      count: pendingDeletions.length,
      requestId: context.requestId 
    });

    let successCount = 0;
    let errorCount = 0;

    for (const deletion of pendingDeletions) {
      try {
        edgeLogger.info('Processing deletion for user', { 
          userId: deletion.user_id,
          requestId: context.requestId 
        });

        // Get user email for confirmation email
        const { data: userData } = await supabase.auth.admin.getUserById(deletion.user_id);
        const userEmail = userData?.user?.email;

        // Delete reviews (CASCADE will handle review_photos)
        await supabase
          .from('reviews')
          .delete()
          .eq('user_id', deletion.user_id);

        // Anonymize submissions and photos
        await supabase
          .rpc('anonymize_user_submissions', { target_user_id: deletion.user_id });

        // Delete user roles
        await supabase
          .from('user_roles')
          .delete()
          .eq('user_id', deletion.user_id);

        // Get profile to check for avatar before deletion
        const { data: profile } = await supabase
          .from('profiles')
          .select('avatar_image_id')
          .eq('user_id', deletion.user_id)
          .maybeSingle();

        // Delete avatar from Cloudflare Images if it exists
        if (profile?.avatar_image_id) {
          const cloudflareAccountId = Deno.env.get('VITE_CLOUDFLARE_ACCOUNT_ID');
          const cloudflareApiToken = Deno.env.get('CLOUDFLARE_API_TOKEN');

          if (cloudflareAccountId && cloudflareApiToken) {
            try {
              edgeLogger.info('Deleting avatar image', { 
                avatarId: profile.avatar_image_id,
                requestId: context.requestId 
              });
              const deleteResponse = await fetch(
                `https://api.cloudflare.com/client/v4/accounts/${cloudflareAccountId}/images/v1/${profile.avatar_image_id}`,
                {
                  method: 'DELETE',
                  headers: {
                    'Authorization': `Bearer ${cloudflareApiToken}`,
                  },
                }
              );

              if (!deleteResponse.ok) {
                edgeLogger.error('Failed to delete avatar from Cloudflare', { 
                  error: await deleteResponse.text(),
                  requestId: context.requestId 
                });
              } else {
                edgeLogger.info('Avatar deleted from Cloudflare successfully', { 
                  requestId: context.requestId 
                });
              }
            } catch (avatarError) {
              edgeLogger.error('Error deleting avatar from Cloudflare', { 
                error: avatarError,
                requestId: context.requestId 
              });
            }
          }
        }

        // Delete profile
        await supabase
          .from('profiles')
          .delete()
          .eq('user_id', deletion.user_id);

        // Remove from Novu before deleting auth user
        try {
          edgeLogger.info('Removing Novu subscriber', { 
            userId: deletion.user_id,
            requestId: context.requestId 
          });
          
          const { error: novuError } = await supabase.functions.invoke(
            'remove-novu-subscriber',
            {
              body: { 
                subscriberId: deletion.user_id,
                deleteSubscriber: true
              }
            }
          );
          
          if (novuError) {
            edgeLogger.error('Failed to remove Novu subscriber', { 
              error: novuError,
              requestId: context.requestId 
            });
          } else {
            edgeLogger.info('Novu subscriber removed successfully', { 
              requestId: context.requestId 
            });
          }
        } catch (novuError) {
          edgeLogger.error('Error removing Novu subscriber', { 
            error: novuError,
            requestId: context.requestId 
          });
        }

        // Update deletion request status
        await supabase
          .from('account_deletion_requests')
          .update({
            status: 'completed',
            completed_at: new Date().toISOString(),
          })
          .eq('id', deletion.id);

        // Delete auth user
        await supabase.auth.admin.deleteUser(deletion.user_id);

        // Send final confirmation email if we have the email
        if (userEmail) {
          const forwardEmailKey = Deno.env.get('FORWARDEMAIL_API_KEY');
          const fromEmail = Deno.env.get('FROM_EMAIL_ADDRESS') || 'noreply@thrillwiki.com';

          if (forwardEmailKey) {
            try {
              await fetch('https://api.forwardemail.net/v1/emails', {
                method: 'POST',
                headers: {
                  'Content-Type': 'application/json',
                  'Authorization': `Basic ${btoa(forwardEmailKey + ':')}`,
                },
                body: JSON.stringify({
                  from: fromEmail,
                  to: userEmail,
                  subject: 'Account Deletion Completed',
                  html: `
                    <h2>Account Deletion Completed</h2>
                    <p>Your account has been automatically deleted as scheduled on ${new Date().toLocaleDateString()}.</p>
                    <p>Your profile and reviews have been removed, but your contributions to the database remain preserved.</p>
                    <p>Thank you for being part of our community.</p>
                  `,
                }),
              });
            } catch (emailError) {
              edgeLogger.error('Failed to send confirmation email', { 
                error: emailError,
                requestId: context.requestId 
              });
            }
          }
        }

        successCount++;
        edgeLogger.info('Successfully deleted account for user', { 
          userId: deletion.user_id,
          requestId: context.requestId 
        });
      } catch (error) {
        errorCount++;
        edgeLogger.error('Failed to delete account for user', { 
          userId: deletion.user_id,
          error,
          requestId: context.requestId 
        });
      }
    }

    edgeLogger.info('Processed deletions', { 
      successCount,
      errorCount,
      requestId: context.requestId 
    });

    return new Response(
      JSON.stringify({
        success: true,
        message: `Processed ${successCount} deletion(s)`,
        processed: successCount,
        errors: errorCount,
      }),
      { headers: { 'Content-Type': 'application/json' } }
    );
  }
);
