import { NextResponse } from 'next/server'
import { requireAdmin, getSession } from '@/lib/auth'
import { rollbackUpdate } from '@/lib/update-system'
import { prisma } from '@/lib/db'
import { createAuditLog } from '@/lib/audit'

export async function POST(request: Request) {
  try {
    const adminCheck = await requireAdmin()
    if (adminCheck) return adminCheck

    const session = await getSession()
    const { historyId } = await request.json()

    if (!historyId) {
      return NextResponse.json({ error: 'History ID required' }, { status: 400 })
    }

    // Get the update history record
    const historyRecord = await prisma.updateHistory.findUnique({
      where: { id: historyId }
    })

    if (!historyRecord) {
      return NextResponse.json({ error: 'Update record not found' }, { status: 404 })
    }

    if (!historyRecord.backupPath) {
      return NextResponse.json({ error: 'No backup available for this update' }, { status: 400 })
    }

    if (!historyRecord.rollbackAvailable) {
      return NextResponse.json({ error: 'Rollback not available for this update' }, { status: 400 })
    }

    // Perform the rollback using the update-system function
    const result = await rollbackUpdate(historyId)

    if (!result.success) {
      return NextResponse.json({ error: result.error || 'Rollback failed' }, { status: 500 })
    }

    // Audit log
    await createAuditLog({
      userId: session?.userId,
      action: 'UPDATE_ROLLED_BACK',
      category: 'UPDATE',
      details: { 
        historyId,
        fromVersion: historyRecord.toVersion,
        toVersion: historyRecord.fromVersion,
      },
      ipAddress: request.headers.get('x-forwarded-for') || undefined,
      discordLog: {
        title: 'System Rollback',
        description: `Rolled back from v${historyRecord.toVersion} to v${historyRecord.fromVersion}`,
        fields: [
          { name: 'Performed By', value: session?.userId || 'System', inline: true },
        ]
      }
    })

    return NextResponse.json({ 
      success: true,
      version: historyRecord.fromVersion
    })
  } catch (error) {
    console.error('Rollback failed:', error)
    return NextResponse.json(
      { error: 'Rollback failed' },
      { status: 500 }
    )
  }
}
