import { NextRequest, NextResponse } from 'next/server'
import * as fs from 'fs'
import * as path from 'path'

const commandFile = path.join(process.cwd(), 'task-history.json')

export async function GET(request: NextRequest) {
  const { searchParams } = new URL(request.url)
  const id = searchParams.get('id')
  
  if (!id) {
    return NextResponse.json({ error: 'Missing id' }, { status: 400 })
  }

  try {
    let history = []
    if (fs.existsSync(commandFile)) {
      history = JSON.parse(fs.readFileSync(commandFile, 'utf-8'))
    }

    const entry = history.find((h: any) => h.id === id)
    if (!entry) {
      return NextResponse.json({ error: 'Not found' }, { status: 404 })
    }

    return NextResponse.json({ entry })
  } catch (error) {
    return NextResponse.json({ error: 'Failed to get' }, { status: 500 })
  }
}

export async function POST(request: NextRequest) {
  try {
    const body = await request.json()
    const { id, reply } = body

    if (!id || !reply) {
      return NextResponse.json({ error: 'Missing id or reply' }, { status: 400 })
    }

    let history = []
    if (fs.existsSync(commandFile)) {
      history = JSON.parse(fs.readFileSync(commandFile, 'utf-8'))
    }

    const index = history.findIndex((h: any) => h.id === id)
    if (index === -1) {
      return NextResponse.json({ error: 'Entry not found' }, { status: 404 })
    }

    history[index].reply = reply
    history[index].status = 'replied'
    history[index].repliedAt = new Date().toISOString()

    fs.writeFileSync(commandFile, JSON.stringify(history, null, 2))

    return NextResponse.json({ success: true })
  } catch (error) {
    return NextResponse.json({ error: 'Failed to save reply' }, { status: 500 })
  }
}
