<script setup lang="ts">
import { useMutation, useQuery } from '@vue/apollo-composable';
import OrderStatusBadge from '~/components/orders/OrderStatusBadge.vue';
import {
  BlockOrderDocument,
  ManagerFinalizeOrderDocument,
  ManagerOrdersDocument,
  ManagerSetOrderOfferDocument,
} from '~/composables/graphql/generated';

const { result, refetch } = useQuery(ManagerOrdersDocument, { status: null });

const setOffer = useMutation(ManagerSetOrderOfferDocument);
const finalize = useMutation(ManagerFinalizeOrderDocument);
const block = useMutation(BlockOrderDocument);

async function publishOffer(orderId: string) {
  await setOffer.mutate({
    input: {
      orderId,
      deliveryTerms: 'Доставка 3-5 дней',
      deliveryFee: 1000,
      totalPrice: 12500,
    },
  });
  await refetch();
}

async function approve(orderId: string) {
  await finalize.mutate({ orderId, decision: 'APPROVE' });
  await refetch();
}

async function reject(orderId: string) {
  await finalize.mutate({ orderId, decision: 'REJECT' });
  await refetch();
}

async function blockOrder(orderId: string) {
  await block.mutate({ input: { orderId, reason: 'Нужно уточнение параметров' } });
  await refetch();
}
</script>

<template>
  <section class="space-y-4">
    <h1 class="text-2xl font-bold">Заявки и согласования заказов</h1>
    <article v-for="order in result?.managerOrders ?? []" :key="order.id" class="card bg-base-100 border border-base-300">
      <div class="card-body space-y-3">
        <div class="flex items-center justify-between">
          <h2 class="card-title">{{ order.code }}</h2>
          <OrderStatusBadge :status="order.status" />
        </div>
        <ul class="text-sm">
          <li v-for="item in order.items" :key="item.id">{{ item.productName }} × {{ item.quantity }}</li>
        </ul>
        <div class="flex gap-2 flex-wrap">
          <button class="btn btn-primary" @click="publishOffer(order.id)">Публиковать оффер</button>
          <button class="btn btn-success" @click="approve(order.id)">Approve</button>
          <button class="btn btn-error" @click="reject(order.id)">Reject</button>
          <button class="btn btn-warning" @click="blockOrder(order.id)">Блокировать</button>
        </div>
      </div>
    </article>
  </section>
</template>
