// server/api/users/[id].delete.ts
// Delete user

import Database from 'better-sqlite3';
import { join } from 'path';
import { existsSync } from 'fs';

const getDbPath = () => {
  const dbDir = join(process.cwd(), 'data');
  return join(dbDir, 'users.db');
};

export default defineEventHandler(async (event) => {
  const userId = getRouterParam(event, 'id');

  console.log(`🗑️ Delete user endpoint called for ID: ${userId}`);

  if (!userId) {
    throw createError({
      statusCode: 400,
      statusMessage: "User ID is required",
    });
  }

  try {
    const dbPath = getDbPath();
    
    if (!existsSync(dbPath)) {
      throw createError({
        statusCode: 404,
        statusMessage: "Database not found",
      });
    }

    const db = new Database(dbPath);
    
    // Check if user exists
    const existingUser = db.prepare('SELECT * FROM users WHERE id = ?').get(userId) as any;
    
    if (!existingUser) {
      db.close();
      throw createError({
        statusCode: 404,
        statusMessage: "User not found",
      });
    }

    // Delete user
    db.prepare('DELETE FROM users WHERE id = ?').run(userId);
    
    db.close();
    
    console.log(`✅ User deleted: ${userId}`);
    return { success: true, message: 'User deleted successfully' };
  } catch (error: any) {
    console.error("❌ Error deleting user:", error);
    throw createError({
      statusCode: error.statusCode || 500,
      statusMessage: error.message || "Failed to delete user",
    });
  }
});

