import { NextRequest, NextResponse } from 'next/server'
import { auth } from '@/lib/auth'
import { prisma } from '@/lib/prisma'
import { AutomationMode } from '@prisma/client'
import {
  processAutomation,
  setAutomationMode,
  resumeAutomation,
  pauseAutomation,
  takeManualControl,
  enableAutoMode,
} from '@/lib/services/automation-worker'

/**
 * GET /api/v1/admin/orders/[id]/automation
 * Get current automation status
 */
export async function GET(
  request: NextRequest,
  { params }: { params: Promise<{ id: string }> }
) {
  try {
    const session = await auth()

    if (!session || session.user.userType !== 'staff') {
      return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
    }

    const { id: orderId } = await params

    const order = await prisma.order.findUnique({
      where: { id: orderId },
      select: {
        id: true,
        status: true,
        automationMode: true,
        automationPausedAt: true,
        automationPausedReason: true,
        source: true,
      },
    })

    if (!order) {
      return NextResponse.json({ error: 'Order not found' }, { status: 404 })
    }

    return NextResponse.json({
      mode: order.automationMode,
      pausedAt: order.automationPausedAt,
      pausedReason: order.automationPausedReason,
      source: order.source,
      status: order.status,
    })
  } catch (error) {
    console.error('Error getting automation status:', error)
    return NextResponse.json(
      { error: 'Failed to get automation status' },
      { status: 500 }
    )
  }
}

/**
 * PATCH /api/v1/admin/orders/[id]/automation
 * Change automation mode
 *
 * Body:
 * - action: 'auto' | 'manual' | 'pause' | 'resume'
 * - reason?: string (optional reason for pause)
 */
export async function PATCH(
  request: NextRequest,
  { params }: { params: Promise<{ id: string }> }
) {
  try {
    const session = await auth()

    if (!session || session.user.userType !== 'staff') {
      return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
    }

    const { id: orderId } = await params
    const body = await request.json()

    const { action, reason } = body as { action: string; reason?: string }

    if (!action || !['auto', 'manual', 'pause', 'resume'].includes(action)) {
      return NextResponse.json(
        { error: 'Invalid action. Must be: auto, manual, pause, or resume' },
        { status: 400 }
      )
    }

    // Check order exists
    const order = await prisma.order.findUnique({
      where: { id: orderId },
    })

    if (!order) {
      return NextResponse.json({ error: 'Order not found' }, { status: 404 })
    }

    let result
    switch (action) {
      case 'auto':
        result = await enableAutoMode(orderId)
        break

      case 'manual':
        await takeManualControl(orderId)
        result = { triggered: false, action: 'Switched to manual mode' }
        break

      case 'pause':
        await pauseAutomation(orderId, reason)
        result = { triggered: false, action: 'Automation paused' }
        break

      case 'resume':
        result = await resumeAutomation(orderId)
        break

      default:
        return NextResponse.json({ error: 'Invalid action' }, { status: 400 })
    }

    // Get updated order
    const updatedOrder = await prisma.order.findUnique({
      where: { id: orderId },
      select: {
        id: true,
        status: true,
        automationMode: true,
        automationPausedAt: true,
        automationPausedReason: true,
        source: true,
      },
    })

    return NextResponse.json({
      success: true,
      result,
      automation: {
        mode: updatedOrder?.automationMode,
        pausedAt: updatedOrder?.automationPausedAt,
        pausedReason: updatedOrder?.automationPausedReason,
        source: updatedOrder?.source,
        status: updatedOrder?.status,
      },
    })
  } catch (error) {
    console.error('Error updating automation:', error)
    return NextResponse.json(
      { error: 'Failed to update automation' },
      { status: 500 }
    )
  }
}

/**
 * POST /api/v1/admin/orders/[id]/automation
 * Trigger automation processing (useful for manual refresh)
 */
export async function POST(
  request: NextRequest,
  { params }: { params: Promise<{ id: string }> }
) {
  try {
    const session = await auth()

    if (!session || session.user.userType !== 'staff') {
      return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
    }

    const { id: orderId } = await params

    // Check order exists
    const order = await prisma.order.findUnique({
      where: { id: orderId },
    })

    if (!order) {
      return NextResponse.json({ error: 'Order not found' }, { status: 404 })
    }

    // Process automation
    const result = await processAutomation(orderId)

    // Get updated order
    const updatedOrder = await prisma.order.findUnique({
      where: { id: orderId },
      select: {
        id: true,
        status: true,
        automationMode: true,
        automationPausedAt: true,
        automationPausedReason: true,
      },
    })

    return NextResponse.json({
      success: true,
      result,
      automation: {
        mode: updatedOrder?.automationMode,
        status: updatedOrder?.status,
      },
    })
  } catch (error) {
    console.error('Error processing automation:', error)
    return NextResponse.json(
      { error: 'Failed to process automation' },
      { status: 500 }
    )
  }
}
