import { Router } from "express";

import {
  getAdminKuaishouCloudFulfillmentConfig,
  updateAdminKuaishouCloudFulfillmentConfig,
} from "../../../services/admin/platform-config/service.js";
import type { AdminKuaishouCloudFulfillmentConfigRouteBody } from "../../../types/admin-route-inputs.js";
import { createJsonHandler } from "../shared.js";
import type { JsonRecord } from "./shared.js";

const router = Router();

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

router.post(
  "/kuaishou-cloud-fulfillment",
  createJsonHandler(
    (req) =>
      updateAdminKuaishouCloudFulfillmentConfig(
        req.body as AdminKuaishouCloudFulfillmentConfigRouteBody
      ),
    {
      successMessage: "新履约配置已保存",
      errorMessage: "保存新履约配置失败",
      scope: "[admin/platform-config/kuaishou-cloud-fulfillment]",
      audit: (_req, data) => {
        const result = data as JsonRecord;
        return {
          action: "platform_kuaishou_cloud_fulfillment_updated",
          targetType: "platform_config",
          targetId: "kuaishou_cloud_fulfillment",
          data: {
            itemCount: Array.isArray(result.source?.items)
              ? result.source.items.length
              : 0,
            filePath: String(result.filePath || "").trim(),
          },
        };
      },
    }
  )
);

export default router;
