<template>
  <div>
    <UPageCard>
      <template #body>
        <div>товары {{ `(${cart?.line_items?.length} шт)` }}</div>
        <div v-if="cartSum">
          итого {{ cartSum }}
        </div>
      </template>

      <template #footer>
        <UButton
          class="justify-center text-center w-2xs"
          size="xl"
          :label="pay ? 'оформить заказ' : 'перейти к оформлению'"
          @click="pay ? createOrder() : router.push(`/checkout/delivery`)"
        />
      </template>
    </UPageCard>
  </div>
</template>

<script setup lang="ts">
import type { IBspb } from '~/server/shared/types/bspb'

defineProps({
  pay: {
    type: Boolean,
    default: false,
  },
})

const router = useRouter()
const { cart, cartSum } = useCart()

const createOrder = async () => {
  const { data } = await useFetch<IBspb>('/api/bspb', {
    method: 'POST',
    body: {
      order: {
        typeRid: 'Purchase',
        amount: cartSum,
        currency: 'RUB',
        hppRedirectUrl: `${import.meta.env.VITE_BASE_URL}/cart`,
      },
    },
  })

  const redirectUrl = `${data?.value?.order?.hppUrl}?orderId=${data?.value?.order?.id}&password=${data.value?.order?.password}`
  window.open(redirectUrl, '_blank')
}
</script>
