import { HandlerFunctionArgs, gql } from "businessnxt-dev";

const QUERY_ORDER_DETAILS = gql`
  query CreatedOrderDetails(
    $companyNo: Int
    $orderNo: Int
    $createdBy: String = null
  ) {
    useCompany(no: $companyNo) {
      order(filter: { orderNo: { _eq: $orderNo } }) {
        items {
          orderNo
          orgUnit1
          orgUnit2
          createdByUser @export(as: "createdBy")
          official: joinup_Associate_via_Official {
            employeeNo
            userName
            orgUnit1
            orgUnit2
          }
        }
      }
      associate(
        filter: { employeeNo: { _gt: 0 }, userName: { _eq: $createdBy } }
      ) {
        items {
          employeeNo
          orgUnit1
          orgUnit2
        }
      }
    }
  }
`;

const MUTATION_UPDATE_ORDERS_AND_LINES = gql`
  mutation update(
    $companyNo: Int
    $orderNo: Int
    $orderUpdate: Order_Input
    $orderLineUpdate: OrderLine_Input
  ) {
    useCompany(no: $companyNo) {
      order_update(
        filter: { orderNo: { _eq: $orderNo } }
        value: $orderUpdate
      ) {
        affectedRows
      }
      orderLine_update(
        filter: { orderNo: { _eq: $orderNo } }
        value: $orderLineUpdate
      ) {
        affectedRows
      }
    }
  }
`;

export default async function ({
  event,
  createGraphQLClient,
}: HandlerFunctionArgs<"order", Env>) {
  if (event.event !== "DELETE") {
    const client = await createGraphQLClient();
    const details = await client.request<any>(QUERY_ORDER_DETAILS, {
      companyNo: event.companyNo,
      orderNo: event.primaryKeys.orderNo,
    });
    console.log("details", details);
    const order = details.useCompany?.order?.items?.[0];
    const associate =
      details.useCompany?.order?.items?.[0]?.official ??
      details.useCompany?.associate?.items?.[0];

    const update = {
      orgUnit1:
        order.orgUnit1 !== associate.orgUnit1 ? associate.orgUnit1 : undefined,
      orgUnit2:
        order.orgUnit2 !== associate.orgUnit2 ? associate.orgUnit2 : undefined,
      official: !order.official ? associate.employeeNo : undefined,
    };

    const hasUpdates = Object.values(update).filter((x) => x).length > 0;
    console.log({ order, associate, update, hasUpdates });

    if (hasUpdates) {
      const rsp = await client.request<any>(MUTATION_UPDATE_ORDERS_AND_LINES, {
        companyNo: event.companyNo,
        orderNo: event.primaryKeys.orderNo,
        orderUpdate: update,
        orderLineUpdate: {
          orgUnit1: update.orgUnit1,
          orgUnit2: update.orgUnit2,
        },
      });

      console.log("rsp", rsp);
    }
  }
}