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

export async function POST(request: NextRequest, { params }: { params: Promise<{ id: string }> }) {
  const { id } = await params
  const apiKey = request.headers.get("x-api-key")

  if (!apiKey) {
    return NextResponse.json({ error: "API key required", code: "AUTH_REQUIRED" }, { status: 401 })
  }

  try {
    // Verify API key
    const apiKeyResult = await sql`
      SELECT id FROM external_api_keys
      WHERE api_key = ${apiKey} AND status = 'active'
    `

    if (apiKeyResult.length === 0) {
      return NextResponse.json({ error: "Invalid API key", code: "INVALID_KEY" }, { status: 401 })
    }

    const body = await request.json()
    const { download_id, transaction_id, delivery_status = "confirmed", delivery_note } = body

    if (!download_id && !transaction_id) {
      return NextResponse.json(
        {
          error: "download_id or transaction_id required",
          code: "VALIDATION_ERROR",
        },
        { status: 400 },
      )
    }

    // Update the download record
    let result
    if (download_id) {
      result = await sql`
        UPDATE ringtone_downloads
        SET delivery_status = ${delivery_status},
            delivered_at = NOW(),
            updated_at = NOW()
        WHERE id = ${download_id}
        AND api_key_id = ${apiKeyResult[0].id}
        RETURNING id, transaction_id, customer_phone
      `
    } else {
      result = await sql`
        UPDATE ringtone_downloads
        SET delivery_status = ${delivery_status},
            delivered_at = NOW(),
            updated_at = NOW()
        WHERE transaction_id = ${transaction_id}
        AND api_key_id = ${apiKeyResult[0].id}
        RETURNING id, transaction_id, customer_phone
      `
    }

    if (result.length === 0) {
      return NextResponse.json({ error: "Download not found", code: "NOT_FOUND" }, { status: 404 })
    }

    return NextResponse.json({
      success: true,
      data: {
        download_id: result[0].id,
        transaction_id: result[0].transaction_id,
        customer_phone: result[0].customer_phone,
        delivery_status,
        confirmed_at: new Date().toISOString(),
      },
    })
  } catch (error) {
    console.error("Error confirming delivery:", error)
    return NextResponse.json({ error: "Internal server error", code: "SERVER_ERROR" }, { status: 500 })
  }
}
