import { NextResponse } from 'next/server'
import { prisma } from '@/lib/prisma'
import { safeHandler, requireAuth } from '@/lib/auth'
import { buildQuoteSnapshot } from '@/lib/quote-diff'
import { logAudit } from '@/lib/audit'

export const GET = safeHandler(async (req: Request) => {
  await requireAuth()
  const { searchParams } = new URL(req.url)
  const search = searchParams.get('search') || ''

  const quotes = await prisma.quote.findMany({
    where: search ? {
      OR: [
        { quoteNo: { contains: search, mode: 'insensitive' } },
      ],
    } : undefined,
    include: {
      query: { select: { queryNo: true, leadName: true } },
    },
    orderBy: { createdAt: 'desc' },
  })

  return NextResponse.json(quotes)
})

export const POST = safeHandler(async (req: Request) => {
  const { userId } = await requireAuth()
  const data = await req.json()

  // Find or create number series for quotes
  let series = await prisma.numberSeries.findFirst({ where: { module: 'QUOTE', docType: 'QUOTE' } })
  if (!series) {
    series = await prisma.numberSeries.create({
      data: { prefix: 'QOT', module: 'QUOTE', docType: 'QUOTE', nextNumber: 1, format: '{PREFIX}-{YEAR}-{NUM:4}' }
    })
  }
  const year = new Date().getFullYear()
  const quoteNo = `${series.prefix}-${year}-${String(series.nextNumber).padStart(4, '0')}`

  // Calculate item totals
  const items = (data.items || []).map((item: any, index: number) => {
    const quantity = parseInt(item.quantity) || 1
    const unitCost = parseFloat(item.unitCost) || 0
    const totalCost = quantity * unitCost
    return {
      serviceType: item.serviceType,
      description: item.description || '',
      dayNumber: item.dayNumber ? parseInt(item.dayNumber) : null,
      quantity,
      unitCost,
      totalCost,
      sortOrder: item.sortOrder ?? index,
    }
  })

  // Calculate quote totals
  const subtotal = items.reduce((sum: number, item: any) => sum + item.totalCost, 0)
  const markupPercent = parseFloat(data.markupPercent) || 0
  const taxPercent = parseFloat(data.taxPercent) || 0
  const markup = subtotal * markupPercent / 100
  const taxAmount = (subtotal + markup) * taxPercent / 100
  const totalAmount = subtotal + markup + taxAmount

  // Determine version number for this query
  const existingQuoteCount = await prisma.quote.count({ where: { queryId: data.queryId } })

  const quote = await prisma.quote.create({
    data: {
      quoteNo,
      queryId: data.queryId,
      version: existingQuoteCount + 1,
      validUntil: data.validUntil ? new Date(data.validUntil) : null,
      notes: data.notes || null,
      termsConditions: data.termsConditions || null,
      currency: data.currency || 'USD',
      markupPercent,
      taxPercent,
      subtotal,
      markup,
      taxAmount,
      totalAmount,
      createdById: userId,
      items: {
        create: items,
      },
    },
    include: {
      items: true,
      query: { select: { queryNo: true, leadName: true } },
    },
  })

  // Create initial revision
  await prisma.quoteRevision.create({
    data: {
      quoteId: quote.id,
      revisionNumber: 1,
      changeType: 'CREATED',
      changeSummary: 'Initial quote created',
      snapshotData: JSON.stringify(buildQuoteSnapshot(quote, quote.items)),
      changedById: userId,
    },
  })

  await logAudit({
    action: 'CREATE',
    module: 'QUOTES',
    entity: 'Quote',
    entityId: quote.id,
    description: `Created quote ${quoteNo}`,
    req,
  })

  // Increment the number series
  await prisma.numberSeries.update({ where: { id: series.id }, data: { nextNumber: { increment: 1 } } })

  // Update query stage to QUOTED if currently NEW or IN_PROGRESS
  const query = await prisma.query.findUnique({ where: { id: data.queryId }, select: { stage: true } })
  if (query && (query.stage === 'NEW' || query.stage === 'IN_PROGRESS')) {
    await prisma.query.update({ where: { id: data.queryId }, data: { stage: 'QUOTED' } })
  }

  return NextResponse.json(quote, { status: 201 })
})
