import { MedusaRequest, MedusaResponse } from "@medusajs/framework/http"

export async function POST(
  req: MedusaRequest,
  res: MedusaResponse
) {
  const { origin, destination, weight, courier, price } = req.body as Record<string, any>

  if (!origin || !destination || !weight || !courier) {
    return res.status(400).json({
      message: "Missing required fields: origin, destination, weight, courier",
    })
  }

  const apiKey = process.env.RAJAONGKIR_API_KEY

  if (!apiKey) {
    return res.status(500).json({
      message: "RajaOngkir API key not configured",
    })
  }

  const body = new URLSearchParams({
    origin: String(origin),
    destination: String(destination),
    weight: String(weight),
    courier: String(courier),
  })

  if (price) {
    body.append("price", String(price))
  }

  const response = await fetch(
    "https://rajaongkir.komerce.id/api/v1/calculate/domestic-cost",
    {
      method: "POST",
      headers: {
        key: apiKey,
        "Content-Type": "application/x-www-form-urlencoded",
      },
      body: body.toString(),
    }
  )

  const result = await response.json()

  res.json(result)
}
