/**
 * POST /delete-account - Request permanent account deletion (30-day waiting period)
 * POST /delete-account/cancel - Cancel a pending deletion request
 *
 * Design intent:
 * - Allows users to request permanent account deletion
 * - 30-day waiting period before actual deletion
 * - Users can cancel the request within 30 days
 * - After 30 days, account is permanently deleted by a scheduled job
 */

import { serve } from 'https://deno.land/std@0.177.0/http/server.ts';
import { createSupabaseClient } from '../_shared/supabase-client.ts';

const ALLOWED_ORIGIN = Deno.env.get('ALLOWED_ORIGIN') || 'https://sojorn.net';

serve(async (req) => {
  if (req.method === 'OPTIONS') {
    return new Response(null, {
      headers: {
        'Access-Control-Allow-Origin': ALLOWED_ORIGIN,
        'Access-Control-Allow-Methods': 'POST',
        'Access-Control-Allow-Headers': 'authorization, x-client-info, apikey, content-type',
      },
    });
  }

  try {
    const authHeader = req.headers.get('Authorization');
    if (!authHeader) {
      return new Response(JSON.stringify({ error: 'Missing authorization header' }), {
        status: 401,
        headers: {
          'Content-Type': 'application/json',
          'Access-Control-Allow-Origin': ALLOWED_ORIGIN,
        },
      });
    }

    const supabase = createSupabaseClient(authHeader);
    const {
      data: { user },
      error: authError,
    } = await supabase.auth.getUser();

    if (authError || !user) {
      return new Response(JSON.stringify({ error: 'Unauthorized' }), {
        status: 401,
        headers: {
          'Content-Type': 'application/json',
          'Access-Control-Allow-Origin': ALLOWED_ORIGIN,
        },
      });
    }

    if (req.method !== 'POST') {
      return new Response(JSON.stringify({ error: 'Method not allowed' }), {
        status: 405,
        headers: {
          'Content-Type': 'application/json',
          'Access-Control-Allow-Origin': ALLOWED_ORIGIN,
        },
      });
    }

    const url = new URL(req.url);
    const isCancel = url.pathname.endsWith('/cancel');

    if (isCancel) {
      // Cancel deletion request
      const { data, error } = await supabase
        .rpc('cancel_account_deletion', { p_user_id: user.id });

      if (error) {
        console.error('Error cancelling deletion:', error);
        return new Response(JSON.stringify({
          error: 'Failed to cancel deletion request',
          details: error.message
        }), {
          status: 500,
          headers: {
            'Content-Type': 'application/json',
            'Access-Control-Allow-Origin': ALLOWED_ORIGIN,
          },
        });
      }

      if (!data || !data.success) {
        return new Response(JSON.stringify({
          error: data?.error || 'No pending deletion request found'
        }), {
          status: 400,
          headers: {
            'Content-Type': 'application/json',
            'Access-Control-Allow-Origin': ALLOWED_ORIGIN,
          },
        });
      }

      return new Response(
        JSON.stringify({
          success: true,
          message: 'Account deletion request cancelled successfully',
        }),
        {
          status: 200,
          headers: {
            'Content-Type': 'application/json',
            'Access-Control-Allow-Origin': ALLOWED_ORIGIN,
          },
        }
      );
    } else {
      // Request account deletion
      const { data, error } = await supabase
        .rpc('request_account_deletion', { p_user_id: user.id });

      if (error) {
        console.error('Error requesting deletion:', error);
        return new Response(JSON.stringify({
          error: 'Failed to request account deletion',
          details: error.message
        }), {
          status: 500,
          headers: {
            'Content-Type': 'application/json',
            'Access-Control-Allow-Origin': ALLOWED_ORIGIN,
          },
        });
      }

      if (!data || !data.success) {
        return new Response(JSON.stringify({
          error: data?.error || 'Account deletion already requested'
        }), {
          status: 400,
          headers: {
            'Content-Type': 'application/json',
            'Access-Control-Allow-Origin': ALLOWED_ORIGIN,
          },
        });
      }

      return new Response(
        JSON.stringify({
          success: true,
          message: 'Account deletion requested. Your account will be permanently deleted in 30 days. You can cancel this request anytime by logging in.',
          deletion_date: data.deletion_date,
          deletion_requested_at: data.deletion_requested_at,
        }),
        {
          status: 200,
          headers: {
            'Content-Type': 'application/json',
            'Access-Control-Allow-Origin': ALLOWED_ORIGIN,
          },
        }
      );
    }
  } catch (error) {
    console.error('Unexpected error:', error);
    return new Response(JSON.stringify({ error: 'Internal server error' }), {
      status: 500,
      headers: {
        'Content-Type': 'application/json',
        'Access-Control-Allow-Origin': ALLOWED_ORIGIN,
      },
    });
  }
});
