import { NextResponse } from 'next/server'
import fs from 'fs'
import path from 'path'

// Persistent storage for positions using JSON file
const POSITIONS_FILE = path.join(process.cwd(), 'data', 'positions.json')

// Helper functions for persistent storage
function loadPositions() {
  try {
    if (fs.existsSync(POSITIONS_FILE)) {
      const data = fs.readFileSync(POSITIONS_FILE, 'utf8')
      return JSON.parse(data)
    }
  } catch (error) {
    console.error('Error loading positions:', error)
  }
  return []
}

function savePositions(positions) {
  try {
    fs.writeFileSync(POSITIONS_FILE, JSON.stringify(positions, null, 2))
  } catch (error) {
    console.error('Error saving positions:', error)
  }
}

export async function DELETE(request, { params }) {
  try {
    const { positionId } = params

    if (!positionId) {
      return NextResponse.json({
        success: false,
        error: 'Position ID is required'
      }, { status: 400 })
    }

    // Load existing positions
    const activePositions = loadPositions()
    
    // Find and remove the position
    const positionIndex = activePositions.findIndex(pos => pos.id === positionId)
    
    if (positionIndex === -1) {
      return NextResponse.json({
        success: false,
        error: 'Position not found'
      }, { status: 404 })
    }

    const removedPosition = activePositions[positionIndex]
    activePositions.splice(positionIndex, 1)
    savePositions(activePositions)

    console.log(`🗑️  Removed incorrect position: ${removedPosition.symbol} (${positionId})`)

    return NextResponse.json({
      success: true,
      message: `Position ${positionId} removed successfully`,
      removedPosition
    })

  } catch (error) {
    console.error('Error deleting position:', error)
    return NextResponse.json({
      success: false,
      error: 'Failed to delete position'
    }, { status: 500 })
  }
}
