import { NextRequest, NextResponse } from 'next/server'
import { auth } from '@/lib/auth'
import { prisma } from '@/lib/prisma'
import {
  getErrorRules,
  createErrorRule,
  seedDefaultRules,
} from '@/lib/services/error-detection-service'
import type { ErrorSeverity } from '@prisma/client'

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

  const { id: clientId } = await params

  // Verify client exists
  const client = await prisma.enterpriseClient.findUnique({
    where: { id: clientId },
  })

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

  try {
    const rules = await getErrorRules(clientId)
    return NextResponse.json(rules)
  } catch (error) {
    console.error('Failed to get error rules:', error)
    return NextResponse.json(
      { error: 'Failed to get error rules' },
      { status: 500 }
    )
  }
}

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

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

  // Verify client exists
  const client = await prisma.enterpriseClient.findUnique({
    where: { id: clientId },
  })

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

  // Check if this is a request to seed default rules
  if (body.seedDefaults === true) {
    try {
      const count = await seedDefaultRules(clientId)
      return NextResponse.json({
        success: true,
        message: `Seeded ${count} default rules`,
        count,
      })
    } catch (error) {
      console.error('Failed to seed default rules:', error)
      return NextResponse.json(
        { error: 'Failed to seed default rules' },
        { status: 500 }
      )
    }
  }

  // Validate required fields
  if (!body.name || typeof body.name !== 'string') {
    return NextResponse.json({ error: 'Name is required' }, { status: 400 })
  }

  if (!body.pattern || typeof body.pattern !== 'string') {
    return NextResponse.json({ error: 'Pattern is required' }, { status: 400 })
  }

  // 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 createErrorRule(clientId, {
      name: body.name,
      pattern: body.pattern,
      severity: body.severity,
      description: body.description,
    })

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