import { NextRequest, NextResponse } from 'next/server'
import { auth } from '@/lib/auth'
import { prisma } from '@/lib/prisma'
import {
  getErrorRule,
  updateErrorRule,
  deleteErrorRule,
} from '@/lib/services/error-detection-service'
import type { ErrorSeverity } from '@prisma/client'

// GET /api/v1/admin/enterprise-clients/[id]/error-rules/[ruleId]
// Get a specific error detection rule
export async function GET(
  request: NextRequest,
  { params }: { params: Promise<{ id: string; ruleId: string }> }
) {
  const session = await auth()
  if (!session || session.user.userType !== 'staff') {
    return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
  }

  const { id: clientId, ruleId } = await params

  // Verify rule belongs to client
  const rule = await prisma.errorDetectionRule.findFirst({
    where: {
      id: ruleId,
      clientId,
    },
  })

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

  try {
    const ruleWithCount = await getErrorRule(ruleId)
    return NextResponse.json(ruleWithCount)
  } catch (error) {
    console.error('Failed to get error rule:', error)
    return NextResponse.json(
      { error: 'Failed to get error rule' },
      { status: 500 }
    )
  }
}

// PATCH /api/v1/admin/enterprise-clients/[id]/error-rules/[ruleId]
// Update an error detection rule
export async function PATCH(
  request: NextRequest,
  { params }: { params: Promise<{ id: string; ruleId: string }> }
) {
  const session = await auth()
  if (!session || session.user.userType !== 'staff') {
    return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
  }

  const { id: clientId, ruleId } = await params
  const body = await request.json()

  // Verify rule belongs to client
  const existingRule = await prisma.errorDetectionRule.findFirst({
    where: {
      id: ruleId,
      clientId,
    },
  })

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

  // Validate severity if provided
  const validSeverities: ErrorSeverity[] = ['INFO', 'WARNING', 'ERROR', 'CRITICAL']
  if (body.severity && !validSeverities.includes(body.severity)) {
    return NextResponse.json(
      { error: 'Invalid severity. Must be one of: INFO, WARNING, ERROR, CRITICAL' },
      { status: 400 }
    )
  }

  try {
    const rule = await updateErrorRule(ruleId, {
      name: body.name,
      pattern: body.pattern,
      severity: body.severity,
      description: body.description,
      isActive: body.isActive,
    })

    return NextResponse.json(rule)
  } catch (error) {
    console.error('Failed to update error rule:', error)
    return NextResponse.json(
      { error: error instanceof Error ? error.message : 'Failed to update error rule' },
      { status: 400 }
    )
  }
}

// DELETE /api/v1/admin/enterprise-clients/[id]/error-rules/[ruleId]
// Delete an error detection rule
export async function DELETE(
  request: NextRequest,
  { params }: { params: Promise<{ id: string; ruleId: string }> }
) {
  const session = await auth()
  if (!session || session.user.userType !== 'staff') {
    return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
  }

  const { id: clientId, ruleId } = await params

  // Verify rule belongs to client
  const rule = await prisma.errorDetectionRule.findFirst({
    where: {
      id: ruleId,
      clientId,
    },
  })

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

  try {
    await deleteErrorRule(ruleId)
    return NextResponse.json({ success: true })
  } catch (error) {
    console.error('Failed to delete error rule:', error)
    return NextResponse.json(
      { error: 'Failed to delete error rule' },
      { status: 500 }
    )
  }
}
