import { NextRequest, NextResponse } from "next/server"
import { getSessionUser } from "@/lib/auth"
import { query } from "@/lib/db"

export async function POST(request: NextRequest, { params }: { params: Promise<{ id: string }> }) {
  try {
    const user = await getSessionUser()
    if (!user) return NextResponse.json({ error: "Unauthorized" }, { status: 401 })

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

    const maxOrder = await query(
      "SELECT COALESCE(MAX(sort_order), 0) + 1 AS next_order FROM proposal_items WHERE proposal_id = $1",
      [id]
    )

    const quantity = body.quantity || 1
    const unitPrice = body.unitPrice || 0
    const discountPercent = body.discountPercent || 0
    const totalPrice = quantity * unitPrice * (1 - discountPercent / 100)

    const result = await query(
      `INSERT INTO proposal_items (proposal_id, product_id, description, quantity, unit_price, discount_percent, total_price, sort_order)
       VALUES ($1, $2, $3, $4, $5, $6, $7, $8) RETURNING id`,
      [id, body.productId || null, body.description, quantity, unitPrice, discountPercent, totalPrice, maxOrder.rows[0].next_order]
    )

    await recalcProposal(id)

    return NextResponse.json({ success: true, id: result.rows[0].id }, { status: 201 })
  } catch (error) {
    console.error("Proposal items POST error:", error)
    return NextResponse.json({ error: "Failed to add item" }, { status: 500 })
  }
}

export async function DELETE(request: NextRequest, { params }: { params: Promise<{ id: string }> }) {
  try {
    await getSessionUser()
    const { id } = await params
    const { searchParams } = new URL(request.url)
    const itemId = searchParams.get("itemId")
    if (!itemId) return NextResponse.json({ error: "itemId required" }, { status: 400 })

    await query("DELETE FROM proposal_items WHERE id = $1 AND proposal_id = $2", [itemId, id])
    await recalcProposal(id)

    return NextResponse.json({ success: true })
  } catch (error) {
    console.error("Proposal items DELETE error:", error)
    return NextResponse.json({ error: "Failed to delete item" }, { status: 500 })
  }
}

async function recalcProposal(proposalId: string) {
  const items = await query(
    "SELECT COALESCE(SUM(total_price), 0) AS subtotal FROM proposal_items WHERE proposal_id = $1",
    [proposalId]
  )
  const subtotal = parseFloat(items.rows[0].subtotal)
  const prop = await query("SELECT tax_percent FROM proposals WHERE id = $1", [proposalId])
  const taxPercent = parseFloat(prop.rows[0]?.tax_percent || 15)
  const taxAmount = subtotal * (taxPercent / 100)
  const totalAmount = subtotal + taxAmount

  await query(
    `UPDATE proposals SET subtotal = $1, tax_amount = $2, total_amount = $3, updated_at = NOW() WHERE id = $4`,
    [subtotal, taxAmount, totalAmount, proposalId]
  )
}
