/**
 * POST /deactivate-account - Deactivate user account (reactivatable within 30 days)
 * POST /deactivate-account/reactivate - Reactivate a deactivated account
 *
 * Design intent:
 * - Allows users to temporarily deactivate their account
 * - Account can be reactivated by logging in
 * - Profile and posts are hidden while deactivated
 */

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 isReactivate = url.pathname.endsWith('/reactivate');

    if (isReactivate) {
      // Reactivate account
      const { data, error } = await supabase
        .rpc('reactivate_account', { p_user_id: user.id });

      if (error) {
        console.error('Error reactivating account:', error);
        return new Response(JSON.stringify({
          error: 'Failed to reactivate account',
          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 is not deactivated'
        }), {
          status: 400,
          headers: {
            'Content-Type': 'application/json',
            'Access-Control-Allow-Origin': ALLOWED_ORIGIN,
          },
        });
      }

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

      if (error) {
        console.error('Error deactivating account:', error);
        return new Response(JSON.stringify({
          error: 'Failed to deactivate account',
          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 already deactivated'
        }), {
          status: 400,
          headers: {
            'Content-Type': 'application/json',
            'Access-Control-Allow-Origin': ALLOWED_ORIGIN,
          },
        });
      }

      return new Response(
        JSON.stringify({
          success: true,
          message: 'Account deactivated successfully. You can reactivate it anytime by logging in.',
          deactivated_at: data.deactivated_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,
      },
    });
  }
});
