// ── Users: Single User ───────────────────────────────────────────────────────
// DELETE /api/users/[id]  — Soft-delete a user account
//
// Auth: super_admin only; cannot delete yourself

import { NextRequest, NextResponse } from "next/server"
import { query } from "@/lib/db"
import { getSessionUser } from "@/lib/auth"

// ── DELETE ───────────────────────────────────────────────────────────────────

export async function DELETE(request: NextRequest, { params }: { params: Promise<{ id: string }> }) {
  try {
    const sessionUser = await getSessionUser()
    if (!sessionUser) {
      return NextResponse.json({ error: "Not authenticated" }, { status: 401 })
    }
    if (sessionUser.role !== "super_admin") {
      return NextResponse.json({ error: "Only super admins can delete users" }, { status: 403 })
    }

    const { id } = await params

    // Prevent self-deletion to avoid admin lockout
    if (id === sessionUser.id) {
      return NextResponse.json({ error: "Cannot delete yourself" }, { status: 400 })
    }

    // Soft-delete: set deleted_at rather than removing the row
    await query(
      `UPDATE users SET deleted_at = NOW() WHERE id = $1 AND deleted_at IS NULL`,
      [id]
    )

    return NextResponse.json({ success: true }, { status: 200 })
  } catch (error) {
    console.error("Error deleting user:", error)
    return NextResponse.json({ error: "Failed to delete user" }, { status: 500 })
  }
}
