import { Router } from "express";

import {
  getAdminFulfillmentBindingConfigs,
  lookupAdminFulfillmentBindingOrder,
  updateAdminFulfillmentBindingConfigs,
} from "../../../services/admin/platform-config/service.js";
import type {
  AdminFulfillmentBindingConfigRouteBody,
  AdminFulfillmentBindingLookupRouteBody,
} from "../../../types/admin-route-inputs.js";
import { createJsonHandler } from "../shared.js";
import type { JsonRecord } from "./shared.js";

const router = Router();

router.get(
  "/fulfillment-bindings",
  createJsonHandler(() => getAdminFulfillmentBindingConfigs(), {
    successMessage: "ok",
    errorMessage: "读取履约配置失败",
    scope: "[admin/platform-config/fulfillment-bindings]",
  })
);

router.post(
  "/fulfillment-bindings/lookup-order",
  createJsonHandler(
    (req) =>
      lookupAdminFulfillmentBindingOrder(
        req.body as AdminFulfillmentBindingLookupRouteBody
      ),
    {
      successMessage: "订单商品查询成功",
      errorMessage: "手动查询订单商品失败",
      scope: "[admin/platform-config/fulfillment-bindings/lookup-order]",
      audit: (req, data) => {
        const result = data as JsonRecord;
        return {
          action: "platform_fulfillment_order_lookup",
          targetType: "platform_config",
          targetId: [
            result.order?.provider || "unknown",
            result.order?.platform || "unknown",
            result.order?.shopId || "unknown",
            result.order?.platformOrderId || "unknown",
          ].join(":"),
          data: {
            itemCount: Array.isArray(result.items) ? result.items.length : 0,
            shopId:
              result.order?.shopId ||
              String(
                (req.body as AdminFulfillmentBindingLookupRouteBody)?.shopId ||
                  ""
              ).trim(),
            platformOrderId:
              result.order?.platformOrderId ||
              String(
                (req.body as AdminFulfillmentBindingLookupRouteBody)
                  ?.platformOrderId || ""
              ).trim(),
          },
        };
      },
    }
  )
);

router.post(
  "/fulfillment-bindings",
  createJsonHandler(
    (req) =>
      updateAdminFulfillmentBindingConfigs(
        req.body as AdminFulfillmentBindingConfigRouteBody
      ),
    {
      successMessage: "履约配置已保存",
      errorMessage: "保存履约配置失败",
      scope: "[admin/platform-config/fulfillment-bindings]",
      audit: (_req, data) => {
        const result = data as JsonRecord;
        return {
          action: "platform_fulfillment_config_updated",
          targetType: "platform_config",
          targetId: "fulfillment_bindings",
          data: {
            bindingCount: Array.isArray(result.bindings)
              ? result.bindings.length
              : 0,
            filePath: result.filePath || "",
          },
        };
      },
    }
  )
);

export default router;
