import { del } from '@vercel/blob';
import { sql } from '@vercel/postgres';
import { getUserFromRequest } from '../../../lib/permission-middleware';

export default async function handler(req, res) {
  if (req.method !== 'DELETE') {
    return res.status(405).json({ error: 'Method not allowed' });
  }

  try {
    // Get authenticated user
    const user = await getUserFromRequest(req);
    if (!user) {
      return res.status(401).json({ error: 'Authentication required' });
    }

    // Prevent admin users from deleting their own accounts
    if (user.role === 'admin') {
      return res.status(403).json({ 
        error: 'Admin accounts cannot be self-deleted. Please contact another administrator.' 
      });
    }

    try {
      // Start transaction-like cleanup
      console.log(`Starting account deletion for user ${user.userId}`);

      // 1. Delete user avatars from Vercel Blob
      const avatarsResult = await sql`
        SELECT file_path FROM user_avatars 
        WHERE user_id = ${user.userId} AND is_active = true
      `;

      for (const avatar of avatarsResult.rows) {
        try {
          await del(avatar.file_path);
          console.log(`Deleted avatar: ${avatar.file_path}`);
        } catch (blobError) {
          console.warn(`Failed to delete avatar blob: ${avatar.file_path}`, blobError);
          // Continue with deletion even if blob cleanup fails
        }
      }

      // 2. Delete user data in correct order (respecting foreign key constraints)
      
      // Delete deck cards first
      await sql`DELETE FROM deck_cards WHERE deck_id IN (SELECT id FROM decks WHERE user_id = ${user.userId})`;
      console.log('Deleted deck cards');

      // Delete decks
      await sql`DELETE FROM decks WHERE user_id = ${user.userId}`;
      console.log('Deleted decks');

      // Delete collection cards
      await sql`DELETE FROM collection_cards WHERE collection_id IN (SELECT id FROM collections WHERE user_id = ${user.userId})`;
      console.log('Deleted collection cards');

      // Delete collections
      await sql`DELETE FROM collections WHERE user_id = ${user.userId}`;
      console.log('Deleted collections');

      // Delete user cards
      await sql`DELETE FROM user_cards WHERE user_id = ${user.userId}`;
      console.log('Deleted user cards');

      // Delete user avatars records
      await sql`DELETE FROM user_avatars WHERE user_id = ${user.userId}`;
      console.log('Deleted user avatar records');

      // Delete user settings
      await sql`DELETE FROM user_settings WHERE user_id = ${user.userId}`;
      console.log('Deleted user settings');

      // Finally, delete the user account
      const deleteResult = await sql`DELETE FROM users WHERE id = ${user.userId}`;
      console.log('Deleted user account');

      if (deleteResult.rowCount === 0) {
        return res.status(404).json({ error: 'User not found' });
      }

      console.log(`Successfully deleted account for user ${user.userId}`);
      res.status(200).json({ 
        message: 'Account deleted successfully. All your data has been permanently removed.' 
      });

    } catch (deleteError) {
      console.error('Account deletion error:', deleteError);
      
      // Check if it's a foreign key constraint error
      if (deleteError.code === '23503') {
        return res.status(400).json({ 
          error: 'Cannot delete account due to data dependencies. Please contact support.' 
        });
      }
      
      res.status(500).json({ error: 'Failed to delete account. Please try again or contact support.' });
    }

  } catch (error) {
    console.error('Account deletion API error:', error);
    res.status(500).json({ error: 'Internal server error' });
  }
} 