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

export async function GET(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 [propResult, itemsResult, sigResult] = await Promise.all([
      query(
        `SELECT p.id, p.title, p.proposal_number, p.subtotal, p.tax_percent, p.tax_amount, p.total_amount,
                p.valid_until, p.notes, p.terms, p.content, p.created_at, p.updated_at,
                ps.id AS status_id, ps.name AS status_name, ps.color AS status_color,
                u.first_name || ' ' || u.last_name AS created_by_name,
                l.id AS lead_id, l.company_name AS lead_company, l.contact_name AS lead_contact,
                c.id AS customer_id, c.company_name
         FROM proposals p
         JOIN proposal_statuses ps ON ps.id = p.status_id
         JOIN users u ON u.id = p.created_by
         LEFT JOIN leads l ON l.id = p.lead_id
         LEFT JOIN customers c ON c.id = p.customer_id
         WHERE p.id = $1 AND p.deleted_at IS NULL`,
        [id]
      ),
      query(
        `SELECT id, product_id, description, quantity, unit_price, discount_percent, total_price, sort_order
         FROM proposal_items WHERE proposal_id = $1 ORDER BY sort_order`,
        [id]
      ),
      query(
        `SELECT id, signatory_name, signatory_email, signed_at FROM proposal_signatures WHERE proposal_id = $1 AND is_valid = true ORDER BY signed_at DESC`,
        [id]
      ),
    ])

    if (propResult.rows.length === 0) {
      return NextResponse.json({ error: "Proposal not found" }, { status: 404 })
    }

    return NextResponse.json({
      ...propResult.rows[0],
      items: itemsResult.rows,
      signatures: sigResult.rows,
    })
  } catch (error) {
    console.error("Proposal detail API error:", error)
    return NextResponse.json({ error: "Failed to load proposal" }, { status: 500 })
  }
}

export async function PATCH(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 fields: string[] = []
    const values: any[] = []
    let idx = 1

    const fieldMap: Record<string, string> = {
      title: "title",
      statusId: "status_id",
      content: "content",
      subtotal: "subtotal",
      taxPercent: "tax_percent",
      taxAmount: "tax_amount",
      totalAmount: "total_amount",
      validUntil: "valid_until",
      notes: "notes",
      terms: "terms",
      leadId: "lead_id",
      customerId: "customer_id",
      opportunityId: "opportunity_id",
    }

    for (const [key, col] of Object.entries(fieldMap)) {
      if (body[key] !== undefined) {
        fields.push(`${col} = $${idx++}`)
        values.push(body[key])
      }
    }

    if (fields.length === 0) {
      return NextResponse.json({ error: "No fields to update" }, { status: 400 })
    }

    fields.push(`updated_at = NOW()`)
    values.push(id)

    await query(
      `UPDATE proposals SET ${fields.join(", ")} WHERE id = $${idx} AND deleted_at IS NULL`,
      values
    )

    return NextResponse.json({ success: true })
  } catch (error) {
    console.error("Proposal PATCH error:", error)
    return NextResponse.json({ error: "Failed to update proposal" }, { status: 500 })
  }
}

export async function DELETE(request: NextRequest, { params }: { params: Promise<{ id: string }> }) {
  try {
    await getSessionUser()
    const { id } = await params
    await query("UPDATE proposals SET deleted_at = NOW() WHERE id = $1", [id])
    return NextResponse.json({ success: true })
  } catch (error) {
    console.error("Proposal DELETE error:", error)
    return NextResponse.json({ error: "Failed to delete proposal" }, { status: 500 })
  }
}
