// register domains & create zaprite order
export default defineEventHandler(async (e) => {

  const body = await readBody(e)

  try {
    
    const details = {
      user: body.user,
      domain: body.domain,
      price: body.price,
      id: crypto.randomUUID()
    }
    
    const checkout = await zapriteOrder(details)
    createInvoice(details, checkout)
    
    const redirect = checkout.checkoutUrl
    
    return { redirect }
  } catch (e){
    console.log(e)
  }
})

// create invoice in CMS
const createInvoice = async (details, checkout) => {

  let url = process.env.DIRECTUS_URL
  let token = process.env.DIRECTUS_TOKEN

  try {
    await $fetch(`${url}/items/invoices`, {
      method: 'POST',
      headers: {
        'Authorization': 'Bearer ' + token,
      },
      body: {
        "user": details.user,
        "price": details.price,
        "product": details.domain,
        "zaprite": checkout.id,
        "status": true,
      }
    })
  } catch (e){
    console.log(e)
  }
}

// create order in zaprite
const zapriteOrder = async (details) => {
  // console.log('The user "' + order.user + '" is registering "' + order.domain + '" for $' + order.price + '.')

  let zaprite = process.env.ZAPRITE_URL
  let token = process.env.ZAPRITE_TOKEN

  try {
    const order = await $fetch(`${zaprite}/v1/order`, {
      method: 'POST',
      headers: {
        'accept': 'application/json',
        'authorization': 'Bearer ' + token,
        'content-type': 'application/json',
      },
      body: {
        'externalUniqId': details.id,
        'amount': details.price * 100,
        'currency': process.env.ZAPRITE_CURRENCY,
        'redirectUrl': process.env.DNS,
        'label': details.domain
      }
    })

    return order
  } catch (e){
    console.log(e)
  }
}