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

export async function POST(request: NextRequest, { params }: { params: Promise<{ id: string }> }) {
  try {
    const { id } = await params
    const body = await request.json()

    const signature = await query(
      `INSERT INTO proposal_signatures (proposal_id, signatory_name, signatory_email, signature_data, ip_address)
       VALUES ($1, $2, $3, $4, $5::inet) RETURNING id`,
      [
        id,
        body.name,
        body.email,
        body.signatureData || null,
        request.headers.get("x-forwarded-for") || request.headers.get("x-real-ip") || "127.0.0.1",
      ]
    )

    const acceptedStatus = await query("SELECT id FROM proposal_statuses WHERE name = 'Accepted'")
    if (acceptedStatus.rows[0]) {
      await query(
        "UPDATE proposals SET status_id = $1, updated_at = NOW() WHERE id = $2",
        [acceptedStatus.rows[0].id, id]
      )
    }

    return NextResponse.json({ success: true, id: signature.rows[0].id })
  } catch (error) {
    console.error("Proposal sign error:", error)
    return NextResponse.json({ error: "Failed to sign proposal" }, { status: 500 })
  }
}
