import http from "./http";
import { encryptLoginPassword } from "../utils/authCrypto";

export const fetchCaptcha = () => http.get("/captcha");
export const login = async (payload: { tenantCode: string; phone: string; password: string; captchaId?: string; captchaCode?: string }) =>
  http.post("/auth/login", {
    ...payload,
    password: await encryptLoginPassword(payload.password),
  });
export const platformLogin = async (payload: { phone: string; password: string; captchaId?: string; captchaCode?: string }) =>
  http.post("/auth/platform-login", {
    ...payload,
    password: await encryptLoginPassword(payload.password),
  });
export const verifyPasswordSetupToken = (params: { tenantCode: string; token: string }) =>
  http.get("/auth/password-setup/verify", { params });
export const completePasswordSetup = (payload: { tenantCode: string; token: string; newPassword: string }) =>
  http.post("/auth/password-setup/complete", payload);
export const refreshAuth = () => http.post("/auth/refresh");
export const fetchSwitchableTenants = () => http.get("/auth/switchable-tenants");
export const switchTenant = (payload: { tenantId: number }) => http.post("/auth/switch-tenant", payload);
export const logoutAuth = () => http.post("/auth/logout");
export const logoutAllAuth = () => http.post("/auth/logout-all");
export const fetchGlobalSearch = (params: { q: string; limitPerType?: number }) => http.get("/search/global", { params });

export const fetchProjects = (params?: { parentOnly?: boolean; includeDeleted?: boolean }) => http.get("/projects", { params });
export const fetchProjectChildren = (id: number, params?: { includeDeleted?: boolean }) => http.get(`/projects/${id}/children`, { params });
export const createProject = (payload: {
  name: string;
  parentProjectId?: number;
  startDate?: string;
  endDate?: string;
  hostEnterpriseName?: string;
  partnerEnterpriseId?: number;
  budgetCent: number;
  meetingTotal: number;
  allowMeetingOverBudget?: boolean;
  overBudgetThresholdRatio?: number;
  overBudgetApprovalChainJson?: string;
  paymentStatus?: string;
  writeOffStatus?: string;
  laborFeeRatio?: number;
  allowProjectOverBudget?: boolean;
  invoiceInfo?: string;
  expenseRatioJson?: string;
  projectFeeJson?: string;
}) => http.post("/projects", payload);
export const updateProject = (
  id: number,
  payload: {
    name: string;
    parentProjectId?: number;
    startDate?: string;
    endDate?: string;
    hostEnterpriseName?: string;
    partnerEnterpriseId?: number;
    budgetCent: number;
    meetingTotal: number;
    allowMeetingOverBudget?: boolean;
    overBudgetThresholdRatio?: number;
    overBudgetApprovalChainJson?: string;
    paymentStatus?: string;
    writeOffStatus?: string;
    laborFeeRatio?: number;
    allowProjectOverBudget?: boolean;
    invoiceInfo?: string;
    expenseRatioJson?: string;
    projectFeeJson?: string;
  },
) => http.put(`/projects/${id}`, payload);
export const freezeProject = (id: number, reason: string) =>
  http.post(`/projects/${id}/freeze`, null, { params: { reason } });
export const unfreezeProject = (id: number, payload: { reason: string }) =>
  http.post(`/projects/${id}/unfreeze`, payload);
export const archiveProject = (id: number) =>
  http.post(`/projects/${id}/archive`);
export const fetchProjectBindingCandidates = () => http.get("/projects/binding-candidates");
export const fetchProjectBindings = (id: number) => http.get(`/projects/${id}/bindings`);
export const fetchProjectKeyChangeLogs = (id: number) => http.get(`/projects/${id}/key-change-logs`);
export const fetchProjectChangeLogs = (id: number) => http.get(`/projects/${id}/key-change-logs`);
export const saveProjectBindings = (
  id: number,
  payload: { ownerUserIds: number[]; executorUserIds: number[]; legacyExecutorUserIds?: number[] },
) => http.post(`/projects/${id}/bindings`, payload);

export const fetchMeetings = (params?: {
  projectId?: number;
  projectName?: string;
  topic?: string;
  meetingStatus?: string;
  auditStatus?: string;
  currentAuditNode?: string;
  currentAuditorUserId?: number;
  meetingStartFrom?: string;
  meetingStartTo?: string;
  lastSubmitFrom?: string;
  lastSubmitTo?: string;
  includeDeleted?: boolean;
}) => http.get("/meetings", { params });
export const fetchMeetingPlatformExperts = (params?: { keyword?: string }) => http.get("/meetings/tenant-experts", { params });
export const createMeetingPlatformExpert = (payload: {
  expertName: string;
  idNo: string;
  phone: string;
  titleCode?: string;
  title?: string;
  hospitalCode?: string;
  organization?: string;
  idCardFrontOssKey?: string;
  idCardBackOssKey?: string;
}) => http.post("/meetings/tenant-experts", payload);
export const addMeetingTenantExpertBankCard = (
  expertId: number,
  payload: {
    bankName: string;
    bankProvince?: string;
    bankCity?: string;
    bankBranchName?: string;
    bankCardNo: string;
    bankCardFrontOssKey?: string;
    bankCardBackOssKey?: string;
    accountName: string;
    isDefault?: boolean;
  },
) => http.post(`/meetings/tenant-experts/${expertId}/bank-cards`, payload);
export const submitMeetingLaborAgreementExtractTask = (
  meetingId: number,
  payload: { objectKey: string; fileName: string },
) => http.post(`/meetings/${meetingId}/labor-agreement-extract/task`, payload);
export const queryMeetingLaborAgreementExtract = (
  meetingId: number,
  payload: { taskId: string },
) => http.post(`/meetings/${meetingId}/labor-agreement-extract/query`, payload);
export const applyMeetingLaborAgreementExtract = (
  meetingId: number,
  payload: {
    taskId: string;
    existingExpertId?: number;
    updateExistingExpert?: boolean;
    objectKey?: string;
    fileName?: string;
  },
) => http.post(`/meetings/${meetingId}/labor-agreement-extract/apply`, payload);
export const fetchMeetingExpertBindings = (meetingId: number) => http.get(`/meetings/${meetingId}/experts`);
export const bindMeetingExperts = (meetingId: number, payload: { expertIds: number[] }) =>
  http.post(`/meetings/${meetingId}/experts/bind`, payload);
export const unbindMeetingExpert = (meetingId: number, expertId: number) =>
  http.delete(`/meetings/${meetingId}/experts/${expertId}`);
export const createMeeting = (payload: {
  projectId: number;
  topic: string;
  budgetCent: number;
  meetingCategory?: string;
  meetingForm?: string;
  location?: string;
  startTime?: string;
  endTime?: string;
  laborRatio?: number;
  cateringRatio?: number;
}) => http.post("/meetings", payload);
export const fetchMeetingDetail = (id: number) => http.get(`/meetings/${id}`);
export const fetchMeetingChangeLogs = (id: number) => http.get(`/meetings/${id}/change-logs`);
export const updateMeeting = (
  id: number,
  payload: {
    projectId: number;
    topic: string;
    budgetCent: number;
    meetingCategory?: string;
    meetingForm?: string;
    location?: string;
    startTime?: string;
    endTime?: string;
    laborRatio?: number;
    cateringRatio?: number;
  },
) => http.put(`/meetings/${id}`, payload);
export const submitMeeting = (id: number, payload: { idempotencyKey: string; remark: string }) =>
  http.post(`/meetings/${id}/submit`, payload);
export const withdrawMeeting = (id: number, payload: { idempotencyKey: string; reason: string }) =>
  http.post(`/meetings/${id}/withdraw`, payload);
export const deleteMeeting = (id: number) =>
  http.post(`/meetings/${id}/delete`);
export const cancelMeeting = (id: number, payload: { reason: string }) =>
  http.post(`/meetings/${id}/cancel`, payload);
export const updateMeetingInvoiceConfig = (id: number, payload: { invoiceModules: string[] }) =>
  http.put(`/meetings/${id}/invoice-config`, payload);
export const fetchMeetingMaterials = (meetingId: number) =>
  http.get(`/meetings/${meetingId}/materials`);
export const fetchMeetingMaterialCurrent = (
  meetingId: number,
  moduleCode: "BASIC_INFO" | "WRITE_OFF_DOCS" | "EXPERT_LIST" | "MEETING_INVOICE",
) => http.get(`/meetings/${meetingId}/materials/${moduleCode}/current`);
export const saveMeetingMaterial = (
  meetingId: number,
  moduleCode: "BASIC_INFO" | "WRITE_OFF_DOCS" | "EXPERT_LIST" | "MEETING_INVOICE",
  payload: { contentJson: string; remark?: string },
) => http.post(`/meetings/${meetingId}/materials/${moduleCode}/save`, payload);
export const submitMeetingMaterial = (
  meetingId: number,
  moduleCode: "BASIC_INFO" | "WRITE_OFF_DOCS" | "EXPERT_LIST" | "MEETING_INVOICE",
  payload: { contentJson: string; remark?: string },
) => http.post(`/meetings/${meetingId}/materials/${moduleCode}/submit`, payload);
export const fetchMeetingMaterialUploadSign = (
  meetingId: number,
  moduleCode: "BASIC_INFO" | "WRITE_OFF_DOCS" | "EXPERT_LIST" | "MEETING_INVOICE",
  payload: { fileName: string; contentType?: string },
) => http.post(`/meetings/${meetingId}/materials/${moduleCode}/upload-sign`, payload);
export const fetchMeetingMaterialHistory = (
  meetingId: number,
  moduleCode: "BASIC_INFO" | "WRITE_OFF_DOCS" | "EXPERT_LIST" | "MEETING_INVOICE",
) => http.get(`/meetings/${meetingId}/materials/${moduleCode}/history`);
export const fetchFilePresignDownload = (params: { objectKey: string }) =>
  http.get("/files/presign-download", { params });

export const recognizeMultipleInvoice = (payload: { objectKey: string }) =>
  http.post("/ocr/multiple-invoice", payload);
export const recognizeIdCard = (payload: { objectKey: string; idCardSide: "front" | "back" }) =>
  http.post("/ocr/id-card", payload);
export const recognizePlatformIdCard = (payload: { objectKey: string; idCardSide: "front" | "back" }) =>
  http.post("/platform/ocr/id-card", payload);
export const recognizeBankCard = (payload: { objectKey: string }) =>
  http.post("/ocr/bank-card", payload);
export const recognizePlatformBankCard = (payload: { objectKey: string }) =>
  http.post("/platform/ocr/bank-card", payload);
export const submitDocumentExtractTask = (payload: {
  objectKey?: string;
  fileName?: string;
  fileUrls?: string[];
  manifestVersionId?: string;
  manifest?: Array<{
    key: string;
    parentKey?: string;
    description?: string;
  }>;
  removeDuplicates?: boolean;
  pageRange?: string;
  extractSeal?: boolean;
  eraseWatermark?: boolean;
}) => http.post("/ocr/document-extract/task", payload);
export const queryDocumentExtractTask = (payload: { taskId: string }) =>
  http.post("/ocr/document-extract/query-task", payload);
export const fetchMeetingMatchedTemplates = (meetingId: number) =>
  http.get(`/meetings/${meetingId}/matched-templates`);
export const createMeetingMaterialsExportTask = (
  meetingId: number,
  payload: { idempotencyKey: string; fileName?: string },
) => http.post(`/meetings/${meetingId}/materials/export`, payload);
export const generateMeetingSummaryTask = (
  meetingId: number,
  payload: { idempotencyKey: string; fileName?: string },
) => http.post(`/meetings/${meetingId}/summary/generate`, payload);
export const fetchMeetingSummaryTaskStatus = (
  meetingId: number,
  params?: { taskId?: number },
) => http.get(`/meetings/${meetingId}/summary/task-status`, { params });
export const refreshMeetingSummaryToken = (
  meetingId: number,
  params: { taskId: number },
) => http.post(`/meetings/${meetingId}/summary/refresh-token`, null, { params });
export const downloadMeetingSummary = (
  meetingId: number,
  params: { taskId: number; token: string },
) => http.get(`/meetings/${meetingId}/summary/download`, { params });

export const fetchAuditTasks = (params?: boolean | {
  mine?: boolean;
  scope?: string;
  meetingId?: number;
  pageNo?: number;
  pageSize?: number;
  sortBy?: string;
  order?: "asc" | "desc";
}) => {
  if (typeof params === "boolean") {
    return http.get("/audits/tasks", { params: { mine: params } });
  }
  return http.get("/audits/tasks", {
    params: {
      mine: !!params?.mine,
      scope: params?.scope,
      meetingId: params?.meetingId,
      pageNo: params?.pageNo,
      pageSize: params?.pageSize,
      sortBy: params?.sortBy,
      order: params?.order,
    },
  });
};
export const exportAuditOpinions = () => http.get("/audits/export-opinions");
export const readAuditTaskMaterial = (
  taskId: number,
  moduleCode: "BASIC_INFO" | "WRITE_OFF_DOCS" | "EXPERT_LIST" | "MEETING_INVOICE" | "EXPERT_PROFILE",
) =>
  http.get(`/audits/tasks/${taskId}/material`, { params: { moduleCode } });
export const approveAuditMaterialModule = (
  taskId: number,
  payload: {
    idempotencyKey: string;
    moduleCode: "BASIC_INFO" | "WRITE_OFF_DOCS" | "EXPERT_PROFILE" | "EXPERT_LIST" | "MEETING_INVOICE";
  },
) => http.post(`/audits/tasks/${taskId}/material/approve-module`, payload);
export const rejectAuditMaterialItem = (
  taskId: number,
  payload: {
    idempotencyKey: string;
    moduleCode: "BASIC_INFO" | "WRITE_OFF_DOCS" | "EXPERT_PROFILE" | "EXPERT_LIST" | "MEETING_INVOICE";
    itemKey: string;
    itemLabel: string;
    reason: string;
  },
) => http.post(`/audits/tasks/${taskId}/material/reject-item`, payload);
export const approveAuditTask = (id: number, payload: { idempotencyKey: string; opinion: string }) =>
  http.post(`/audits/tasks/${id}/approve`, payload);
export const rejectAuditTask = (id: number, payload: { idempotencyKey: string; opinion: string }) =>
  http.post(`/audits/tasks/${id}/reject`, payload);
export const returnAuditTask = (id: number, payload: { idempotencyKey: string; opinion: string }) =>
  http.post(`/audits/tasks/${id}/return`, payload);
export const transferAuditTask = (
  id: number,
  payload: { idempotencyKey: string; toUserId: number; reason: string },
) => http.post(`/audits/tasks/${id}/transfer`, payload);
export const batchRemindAuditTasks = (payload: { idempotencyKey: string; taskIds?: number[] }) =>
  http.post("/audits/tasks/batch-remind", payload);
export const batchApproveAuditTasks = (payload: { idempotencyKey: string; taskIds: number[]; opinion: string }) =>
  http.post("/audits/tasks/batch-approve", payload);
export const batchRejectAuditTasks = (payload: { idempotencyKey: string; taskIds: number[]; opinion: string }) =>
  http.post("/audits/tasks/batch-reject", payload);
export const fetchAuditSlaStat = () => http.get("/audits/tasks/sla-stat");

export const fetchAuditFlows = (params?: { pageNo?: number; pageSize?: number }) =>
  http.get("/audit-flows", { params });
export const createAuditFlow = (payload: {
  flowCode: string;
  flowName: string;
  effectiveStartAt?: string;
  effectiveEndAt?: string;
  nodes: Array<{ nodeCode: string; nodeName: string; sortNo: number; assigneeType?: string; assigneeRefId?: number }>;
}) => http.post("/audit-flows", payload);
export const updateAuditFlow = (
  id: number,
  payload: {
    flowCode: string;
    flowName: string;
    effectiveStartAt?: string;
    effectiveEndAt?: string;
    nodes: Array<{ nodeCode: string; nodeName: string; sortNo: number; assigneeType?: string; assigneeRefId?: number }>;
  },
) => http.put(`/audit-flows/${id}`, payload);
export const copyAuditFlow = (id: number) => http.post(`/audit-flows/${id}/copy`);
export const setDefaultAuditFlow = (id: number) => http.post(`/audit-flows/${id}/default`);
export const enableAuditFlow = (id: number) => http.post(`/audit-flows/${id}/enable`);
export const disableAuditFlow = (id: number) => http.post(`/audit-flows/${id}/disable`);

export const fetchFinanceProjects = () => http.get("/finance/projects");
export const exportFinanceLedger = () => http.get("/finance/ledger/export");
export const reconcileFinance = (payload: { idempotencyKey: string; projectId: number; expectedAmountCent: number }) =>
  http.post("/finance/reconciliation", payload);
export const lockFinance = (payload: { idempotencyKey: string; projectId: number; reason: string }) =>
  http.post("/finance/lock", payload);
export const unlockFinance = (payload: { idempotencyKey: string; projectId: number; reason: string }) =>
  http.post("/finance/unlock", payload);
export const fetchFinanceReconciliationList = (params?: { projectId?: number }) =>
  http.get("/finance/reconciliation/list", { params });
export const confirmPayment = (payload: {
  idempotencyKey: string;
  projectId: number;
  meetingId: number;
  amountCent: number;
  paymentVoucherOssKey: string;
}) => http.post("/finance/payments", payload);

export const fetchUsers = (params?: { pageNo?: number; pageSize?: number; includeDeleted?: boolean; keyword?: string }) => http.get("/users", { params });
export const fetchTenants = () => http.get("/tenants");
export const fetchPlatformTenants = () => http.get("/platform/tenants");
export const createTenant = (payload: { tenantCode: string; tenantName: string; logoUrl?: string }) =>
  http.post("/tenants", payload);
export const updateTenant = (
  id: number,
  payload: { tenantName: string; logoUrl?: string },
) => http.put(`/tenants/${id}`, payload);
export const createPlatformTenant = (payload: { tenantCode: string; tenantName: string; logoUrl?: string }) =>
  http.post("/platform/tenants", payload);
export const updatePlatformTenant = (
  id: number,
  payload: { tenantName: string; logoUrl?: string },
) => http.put(`/platform/tenants/${id}`, payload);
export const fetchTenantLogoUploadSign = (payload: { fileName: string; contentType?: string }) =>
  http.post("/tenants/logo-upload-sign", payload);
export const fetchPlatformTenantLogoUploadSign = (payload: { fileName: string; contentType?: string }) =>
  http.post("/platform/tenants/logo-upload-sign", payload);
export const enableTenant = (id: number) => http.post(`/tenants/${id}/enable`);
export const disableTenant = (id: number) => http.post(`/tenants/${id}/disable`);
export const enablePlatformTenant = (id: number) => http.post(`/platform/tenants/${id}/enable`);
export const disablePlatformTenant = (id: number) => http.post(`/platform/tenants/${id}/disable`);
export const deletePlatformTenant = (id: number) => http.post(`/platform/tenants/${id}/delete`);
export const fetchPlatformTenantAdmin = (id: number) => http.get(`/platform/tenants/${id}/admin`);
export const initPlatformTenantBaseline = (id: number) => http.post(`/platform/tenants/${id}/init-baseline`);
export const setPlatformTenantAdmin = (
  id: number,
  payload: { userName: string; phone: string; email?: string; roleCode?: string },
) => http.post(`/platform/tenants/${id}/admin`, payload);
export const fetchEnterprises = (params?: { pageNo?: number; pageSize?: number }) =>
  http.get("/enterprises", { params });
export const createEnterprise = (payload: { enterpriseName: string; enterpriseUrl?: string; logoUrl?: string }) =>
  http.post("/enterprises", payload);
export const fetchEnterpriseLogoUploadSign = (payload: { fileName: string; contentType?: string }) =>
  http.post("/enterprises/logo-upload-sign", payload);
export const updateEnterprise = (
  id: number,
  payload: { enterpriseName: string; enterpriseUrl?: string; logoUrl?: string },
) => http.put(`/enterprises/${id}`, payload);
export const enableEnterprise = (id: number) => http.post(`/enterprises/${id}/enable`);
export const disableEnterprise = (id: number) => http.post(`/enterprises/${id}/disable`);
export const deleteEnterprise = (id: number) => http.post(`/enterprises/${id}/delete`);
export const createUser = (payload: {
  userName: string;
  phone: string;
  password: string;
  email?: string;
  validFrom?: string;
  validTo?: string;
}) => http.post("/users", payload);
export const updateUser = (
  id: number,
  payload: {
    userName: string;
    phone: string;
    email?: string;
    validFrom?: string;
    validTo?: string;
    password?: string;
  },
) => http.put(`/users/${id}`, payload);
export const assignUserRole = (payload: { userId: number; roleId: number }) =>
  http.post("/users/assign-role", payload);
export const enableUser = (id: number) => http.post(`/users/${id}/enable`);
export const disableUser = (id: number) => http.post(`/users/${id}/disable`);
export const deleteUser = (id: number) => http.post(`/users/${id}/delete`);
export const resetUserPassword = (id: number, payload: { newPassword: string }) =>
  http.post(`/users/${id}/reset-password`, payload);
export const batchImportUsers = (payload: {
  users: Array<{
    userName: string;
    phone: string;
    password: string;
    email?: string;
    validFrom?: string;
    validTo?: string;
    roleCode?: string;
  }>;
}) => http.post("/users/import", payload);
export const fetchUserRoleHistory = (id: number) => http.get(`/users/${id}/role-history`);
export const fetchUserDelegations = (id: number) => http.get(`/users/${id}/delegations`);
export const createUserDelegation = (
  id: number,
  payload: { delegateUserId: number; effectiveFrom: string; effectiveTo: string; reason?: string },
) => http.post(`/users/${id}/delegations`, payload);
export const disableUserDelegation = (id: number, payload: { reason: string }) =>
  http.post(`/delegations/${id}/disable`, payload);
export const changeMyPassword = (payload: { oldPassword: string; newPassword: string }) =>
  http.post("/profile/change-password", payload);
export const fetchProfilePreferences = () => http.get("/profile/preferences");
export const saveProfilePreferences = (payload: { themeMode: string; density: string; themeScheme: string }) =>
  http.put("/profile/preferences", payload);

export const fetchRoles = (params?: { pageNo?: number; pageSize?: number }) =>
  http.get("/roles", { params });
export const createRole = (payload: { roleCode: string; roleName: string }) =>
  http.post("/roles", payload);
export const updateRole = (id: number, payload: { roleName: string }) =>
  http.put(`/roles/${id}`, payload);
export const enableRole = (id: number) => http.post(`/roles/${id}/enable`);
export const disableRole = (id: number) => http.post(`/roles/${id}/disable`);
export const deleteRole = (id: number) => http.post(`/roles/${id}/delete`);
export const fetchPermissions = () => http.get("/permissions");
export const fetchRolePermissions = (id: number) => http.get(`/roles/${id}/permissions`);
export const bindRolePermissions = (id: number, payload: { permissionIds: number[] }) =>
  http.post(`/roles/${id}/permissions`, payload);
export const fetchRoleMenus = (id: number) => http.get(`/roles/${id}/menus`);
export const bindRoleMenus = (id: number, payload: { menuIds: number[] }) =>
  http.post(`/roles/${id}/menus`, payload);
export const fetchMenus = () => http.get("/menus");
export const fetchCurrentMenus = () => http.get("/menus/current");
export const fetchPlatformCurrentMenus = () => http.get("/platform/menus/current");
export const fetchMenuRoles = (id: number) => http.get(`/menus/${id}/roles`);
export const reorderMenus = (payload: { menus: Array<{ id: number; sortNo: number }> }) =>
  http.post("/menus/reorder", payload);
export const createMenu = (payload: {
  menuCode: string;
  menuName: string;
  routePath: string;
  permissionCode: string;
  sortNo: number;
}) =>
  http.post("/menus", payload);
export const updateMenu = (
  id: number,
  payload: {
    menuName: string;
    routePath: string;
    permissionCode: string;
    sortNo: number;
    status: "ENABLED" | "DISABLED";
  },
) => http.put(`/menus/${id}`, payload);

export const fetchDataPermissions = () => http.get("/data-permissions");
export const createDataPermission = (payload: {
  policyName: string;
  projectScope: string;
  projectIdsCsv?: string;
  meetingScope: string;
  meetingIdsCsv?: string;
  userScope: string;
  userIdsCsv?: string;
  expertScope: string;
  expertIdsCsv?: string;
  moduleScope?: string;
  exportAllowed?: boolean;
}) => http.post("/data-permissions", payload);
export const updateDataPermission = (
  id: number,
  payload: {
    policyName: string;
    projectScope: string;
    projectIdsCsv?: string;
    meetingScope: string;
    meetingIdsCsv?: string;
    userScope: string;
    userIdsCsv?: string;
    expertScope: string;
    expertIdsCsv?: string;
    moduleScope?: string;
    exportAllowed?: boolean;
  },
) => http.put(`/data-permissions/${id}`, payload);
export const assignDataPermissionRoles = (id: number, payload: { roleIds: number[]; assignMode?: "APPEND" | "REPLACE" }) =>
  http.post(`/data-permissions/${id}/assign-roles`, payload);
export const copyDataPermission = (id: number) => http.post(`/data-permissions/${id}/copy`);
export const enableDataPermission = (id: number) => http.post(`/data-permissions/${id}/enable`);
export const disableDataPermission = (id: number) => http.post(`/data-permissions/${id}/disable`);
export const fetchDataPermissionRoles = (id: number) => http.get(`/data-permissions/${id}/roles`);
export const fetchCurrentDataScope = () => http.get("/data-permissions/current-scope");
export const fetchAuditLogs = (params?: { userId?: number; actionCode?: string; pageNo?: number; pageSize?: number }) =>
  http.get("/audit-logs", { params });
export const fetchPlatformAuditLogs = (params?: {
  userId?: number;
  actionCode?: string;
  tenantId?: number;
  scope?: "TENANT" | "PLATFORM";
  pageNo?: number;
  pageSize?: number;
}) =>
  http.get("/platform/audit-logs", { params });
export const fetchPlatformRoles = () => http.get("/platform/roles");
export const createPlatformRole = (payload: { roleCode: string; roleName: string }) => http.post("/platform/roles", payload);
export const updatePlatformRole = (id: number, payload: { roleName: string }) => http.put(`/platform/roles/${id}`, payload);
export const enablePlatformRole = (id: number) => http.post(`/platform/roles/${id}/enable`);
export const disablePlatformRole = (id: number) => http.post(`/platform/roles/${id}/disable`);
export const fetchPlatformRolePermissions = (id: number) => http.get(`/platform/roles/${id}/permissions`);
export const bindPlatformRolePermissions = (id: number, payload: { permissionIds: number[] }) =>
  http.post(`/platform/roles/${id}/permissions`, payload);
export const fetchPlatformRoleMenus = (id: number) => http.get(`/platform/roles/${id}/menus`);
export const bindPlatformRoleMenus = (id: number, payload: { menuIds: number[] }) =>
  http.post(`/platform/roles/${id}/menus`, payload);
export const fetchPlatformPermissions = () => http.get("/platform/permissions");
export const fetchPlatformUsers = (params?: { keyword?: string }) => http.get("/platform/users", { params });
export const createPlatformUser = (payload: {
  userName: string;
  phone: string;
  password: string;
  email?: string;
  validFrom?: string;
  validTo?: string;
}) => http.post("/platform/users", payload);
export const batchImportPlatformUsers = (payload: {
  users: Array<{
    userName: string;
    phone: string;
    password: string;
    email?: string;
    validFrom?: string;
    validTo?: string;
    roleCode?: string;
  }>;
}) => http.post("/platform/users/import", payload);
export const assignPlatformUserRole = (payload: { userId: number; roleId: number }) =>
  http.post("/platform/users/assign-role", payload);
export const enablePlatformUser = (id: number) => http.post(`/platform/users/${id}/enable`);
export const disablePlatformUser = (id: number) => http.post(`/platform/users/${id}/disable`);
export const resetPlatformUserPassword = (id: number, payload: { newPassword: string }) =>
  http.post(`/platform/users/${id}/reset-password`, payload);
export const fetchPlatformMenus = () => http.get("/platform/menus");
export const createPlatformMenu = (payload: {
  menuCode: string;
  menuName: string;
  routePath: string;
  permissionCode: string;
  sortNo: number;
}) => http.post("/platform/menus", payload);
export const updatePlatformMenu = (
  id: number,
  payload: {
    menuName: string;
    routePath: string;
    permissionCode: string;
    sortNo: number;
    status: "ENABLED" | "DISABLED";
  },
) => http.put(`/platform/menus/${id}`, payload);
export const reorderPlatformMenus = (payload: { menus: Array<{ id: number; sortNo: number }> }) =>
  http.post("/platform/menus/reorder", payload);
export const fetchPlatformMenuRoles = (id: number) => http.get(`/platform/menus/${id}/roles`);
export const bindPlatformMenuRoles = (id: number, payload: { roleIds: number[] }) =>
  http.post(`/platform/menus/${id}/roles`, payload);
export const exportAuditLogs = (params?: { userId?: number; actionCode?: string }) =>
  http.get("/audit-logs/export", { params });
export const fetchAuditLogExportTasks = () => http.get("/audit-logs/export-tasks");
export const createAuditLogExportTask = (payload: {
  idempotencyKey: string;
  userId?: number;
  actionCode?: string;
  fileName?: string;
}) => http.post("/audit-logs/export-tasks", payload);
export const fetchInvoiceProfiles = () => http.get("/invoice-profiles");
export const createInvoiceProfile = (payload: {
  companyName: string;
  taxNo: string;
  bankName: string;
  accountNo: string;
  address?: string;
  phone?: string;
  defaultProjectId?: number;
  status?: "ENABLED" | "DISABLED";
}) => http.post("/invoice-profiles", payload);
export const updateInvoiceProfile = (
  id: number,
  payload: {
    companyName: string;
    taxNo: string;
    bankName: string;
    accountNo: string;
    address?: string;
    phone?: string;
    defaultProjectId?: number;
    status?: "ENABLED" | "DISABLED";
  },
) => http.put(`/invoice-profiles/${id}`, payload);
export const enableInvoiceProfile = (id: number) => http.post(`/invoice-profiles/${id}/enable`);
export const disableInvoiceProfile = (id: number) => http.post(`/invoice-profiles/${id}/disable`);

export const fetchTemplates = (params?: {
  templateName?: string;
  templateType?: string;
  status?: string;
  scopeType?: string;
  bizScene?: string;
  watermarkEnabled?: boolean;
  effectiveStatus?: string;
  pageNo?: number;
  pageSize?: number;
}) =>
  http.get("/templates", { params });
export const fetchPublishedTemplateOptions = (params?: { bizScene?: string }) =>
  http.get("/templates/published-options", { params });
export const fetchTemplateTypeOptions = () => http.get("/templates/type-options");
export const fetchTemplateFlowSceneOptions = () => http.get("/templates/flow-scene-options");
export const fetchTemplateFlowLinks = () => http.get("/templates/flow-links");
export const bindTemplateFlowLink = (sceneCode: string, payload: { templateId: number }) =>
  http.post(`/templates/flow-links/${sceneCode}/bind`, payload);
export const enableTemplateTypeOption = (typeCode: string) => http.post(`/templates/type-options/${typeCode}/enable`);
export const disableTemplateTypeOption = (typeCode: string) => http.post(`/templates/type-options/${typeCode}/disable`);
export const createTemplate = (payload: {
  templateName: string;
  templateType: string;
  scopeType: "ALL" | "PROJECT" | "MEETING";
  projectId?: number;
  meetingId?: number;
  bizScene?: "MEETING_RECOMMEND" | "AUDIT_NOTIFY" | "SETTLEMENT";
  objectKey: string;
  changeLog?: string;
  effectiveFrom?: string;
  effectiveTo?: string;
  watermarkEnabled?: boolean;
  downloadRateLimitPerHour?: number;
}) => http.post("/templates", payload);
export const fetchTemplateUploadSign = (payload: {
  fileName: string;
  contentType?: string;
  templateType?: string;
}) => http.post("/templates/upload-sign", payload);
export const fetchTemplateVersions = (id: number) => http.get(`/templates/${id}/versions`);
export const addTemplateVersion = (
  id: number,
  payload: {
    objectKey: string;
    changeLog?: string;
  },
) => http.post(`/templates/${id}/versions`, payload);
export const publishTemplate = (id: number) => http.post(`/templates/${id}/publish`);
export const disableTemplate = (id: number) => http.post(`/templates/${id}/disable`);
export const archiveTemplate = (id: number) => http.post(`/templates/${id}/archive`);
export const rollbackTemplate = (id: number, payload: { versionNo: number; rollbackReason: string }) =>
  http.post(`/templates/${id}/rollback`, payload);
export const downloadTemplate = (id: number) => http.get(`/templates/${id}/download`);
export const downloadTemplateWatermark = (id: number, params?: { watermarkText?: string }) =>
  http.get(`/templates/${id}/download-watermark`, { params });
export const fetchTemplateVersionDiff = (id: number, params?: { leftVersionNo?: number; rightVersionNo?: number }) =>
  http.get(`/templates/${id}/versions/diff`, { params });
export const fetchTemplateDownloadLogs = (params?: {
  templateId?: number;
  templateName?: string;
  userId?: number;
  userKeyword?: string;
  versionNo?: number;
  downloadType?: "NORMAL" | "WATERMARK";
  ip?: string;
  downloadedFrom?: string;
  downloadedTo?: string;
  pageNo?: number;
  pageSize?: number;
}) =>
  http.get("/templates/download-logs", { params });

export const fetchExperts = (params?: { keyword?: string; pageNo?: number; pageSize?: number }) => http.get("/experts", { params });
export const fetchPlatformExperts = (params?: { keyword?: string }) => http.get("/platform/experts", { params });
export const fetchExpertDetail = (id: number) => http.get(`/experts/${id}`);
export const fetchPlatformExpertDetail = (id: number) => http.get(`/platform/experts/${id}`);
export const fetchExpertUploadSign = (payload: { fileName: string; contentType?: string }) =>
  http.post("/experts/upload-sign", payload);
export const fetchPlatformExpertUploadSign = (payload: { fileName: string; contentType?: string }) =>
  http.post("/platform/experts/upload-sign", payload);
export const createExpert = (payload: {
  expertName: string;
  idNo: string;
  phone: string;
  titleCode?: string;
  title?: string;
  hospitalCode?: string;
  organization?: string;
}) => http.post("/experts", payload);
export const createPlatformExpert = (payload: {
  expertName: string;
  idNo: string;
  phone: string;
  titleCode?: string;
  title?: string;
  hospitalCode?: string;
  organization?: string;
}) => http.post("/platform/experts", payload);
export const updateExpert = (
  id: number,
  payload: {
    expertName: string;
    idNo: string;
    phone: string;
    titleCode?: string;
    title?: string;
    hospitalCode?: string;
    organization?: string;
    gender?: string;
    birthday?: string;
    idCardValidUntil?: string;
    statusReason?: string;
  },
) => http.put(`/experts/${id}`, payload);
export const updatePlatformExpert = (
  id: number,
  payload: {
    expertName: string;
    idNo: string;
    phone: string;
    titleCode?: string;
    title?: string;
    hospitalCode?: string;
    organization?: string;
    gender?: string;
    birthday?: string;
    idCardValidUntil?: string;
    statusReason?: string;
  },
) => http.put(`/platform/experts/${id}`, payload);
export const importExperts = (payload: {
  experts: Array<{ expertName: string; idNo: string; phone: string; titleCode?: string; title?: string; hospitalCode?: string; organization?: string }>;
}) => http.post("/experts/import", payload);
export const importPlatformExperts = (payload: {
  experts: Array<{ expertName: string; idNo: string; phone: string; titleCode?: string; title?: string; hospitalCode?: string; organization?: string }>;
}) => http.post("/platform/experts/import", payload);
export const exportExperts = () => http.get("/experts/export");
export const exportPlatformExperts = () => http.get("/platform/experts/export");
export const mergeExpert = (id: number, payload: { sourceExpertId: number; reason: string }) =>
  http.post(`/experts/${id}/merge`, payload);
export const mergePlatformExpert = (id: number, payload: { sourceExpertId: number; reason: string }) =>
  http.post(`/platform/experts/${id}/merge`, payload);
export const fetchExpertBankCards = (id: number) => http.get(`/experts/${id}/bank-cards`);
export const fetchPlatformExpertBankCards = (id: number) => http.get(`/platform/experts/${id}/bank-cards`);
export const fetchExpertBankCardDetail = (id: number, cardId: number) => http.get(`/experts/${id}/bank-cards/${cardId}`);
export const fetchPlatformExpertBankCardDetail = (id: number, cardId: number) =>
  http.get(`/platform/experts/${id}/bank-cards/${cardId}`);
export const addExpertBankCard = (
  id: number,
  payload: {
    bankName: string;
    bankProvince?: string;
    bankCity?: string;
    bankBranchName?: string;
    bankCardNo: string;
    bankCardFrontOssKey?: string;
    bankCardBackOssKey?: string;
    accountName: string;
    isDefault?: boolean;
  },
) => http.post(`/experts/${id}/bank-cards`, payload);
export const addPlatformExpertBankCard = (
  id: number,
  payload: {
    bankName: string;
    bankProvince?: string;
    bankCity?: string;
    bankBranchName?: string;
    bankCardNo: string;
    bankCardFrontOssKey?: string;
    bankCardBackOssKey?: string;
    accountName: string;
    isDefault?: boolean;
  },
) => http.post(`/platform/experts/${id}/bank-cards`, payload);
export const updateExpertBankCard = (
  id: number,
  cardId: number,
  payload: {
    bankName: string;
    bankProvince?: string;
    bankCity?: string;
    bankBranchName?: string;
    bankCardNo: string;
    bankCardFrontOssKey?: string;
    bankCardBackOssKey?: string;
    accountName: string;
    isDefault?: boolean;
  },
) => http.put(`/experts/${id}/bank-cards/${cardId}`, payload);
export const updatePlatformExpertBankCard = (
  id: number,
  cardId: number,
  payload: {
    bankName: string;
    bankProvince?: string;
    bankCity?: string;
    bankBranchName?: string;
    bankCardNo: string;
    bankCardFrontOssKey?: string;
    bankCardBackOssKey?: string;
    accountName: string;
    isDefault?: boolean;
  },
) => http.put(`/platform/experts/${id}/bank-cards/${cardId}`, payload);
export const fetchExpertDictionaryOptions = () => http.get("/dictionaries/expert-options");
export const fetchDictionaries = (params?: { dictType?: string; enabledOnly?: boolean }) =>
  http.get("/dictionaries", { params });
export const fetchPlatformDictionaries = (params?: { dictType?: string; enabledOnly?: boolean }) =>
  http.get("/platform/dictionaries", { params });
export const fetchPlatformDictionaryTypes = (params?: { enabledOnly?: boolean }) =>
  http.get("/platform/dictionaries/types", { params });
export const createPlatformDictionaryType = (payload: {
  dictType: string;
  dictName: string;
  sortNo: number;
  remark?: string;
}) => http.post("/platform/dictionaries/types", payload);
export const createPlatformDictionary = (payload: {
  dictType: string;
  dictCode: string;
  dictName: string;
  sortNo: number;
  remark?: string;
}) => http.post("/platform/dictionaries", payload);
export const updatePlatformDictionary = (
  id: number,
  payload: { dictName: string; sortNo: number; status: "ENABLED" | "DISABLED"; remark?: string },
) => http.put(`/platform/dictionaries/${id}`, payload);
export const enablePlatformDictionary = (id: number) => http.post(`/platform/dictionaries/${id}/enable`);
export const disablePlatformDictionary = (id: number) => http.post(`/platform/dictionaries/${id}/disable`);
export const fetchPlatformAuthSessions = (params?: {
  scope?: "TENANT" | "PLATFORM";
  status?: "ACTIVE" | "ROTATED" | "REVOKED" | "EXPIRED";
  userId?: number;
  tenantId?: number;
}) => http.get("/platform/auth-sessions", { params });
export const revokePlatformAuthSession = (id: number) => http.post(`/platform/auth-sessions/${id}/revoke`);
export const revokePlatformPrincipalSessions = (payload: {
  userId: number;
  scope: "TENANT" | "PLATFORM";
  tenantId?: number;
}) => http.post("/platform/auth-sessions/revoke-principal", payload);
export const fetchPlatformNotifyGateways = () => http.get("/platform/notify-gateways");
export const savePlatformNotifyGateway = (
  channelCode: string,
  payload: {
    gatewayName: string;
    providerCode: string;
    status: "ENABLED" | "DISABLED";
    remark?: string;
    config: Record<string, unknown>;
  },
) => http.put(`/platform/notify-gateways/${channelCode}`, payload);
export const testPlatformNotifyGateway = (
  channelCode: string,
  payload: {
    receiverRef: string;
    subject?: string;
    content?: string;
  },
) => http.post(`/platform/notify-gateways/${channelCode}/test`, payload);

export const fetchNotificationPolicies = (params?: { pageNo?: number; pageSize?: number }) =>
  http.get("/notification-policies", { params });
export const fetchNotificationTextTemplates = (params?: { pageNo?: number; pageSize?: number }) =>
  http.get("/notification-text-templates", { params });
export const createNotificationTextTemplate = (payload: {
  templateName: string;
  subjectTemplate?: string;
  titleTemplate?: string;
  contentTemplate: string;
  status?: "ENABLED" | "DISABLED";
}) => http.post("/notification-text-templates", payload);
export const updateNotificationTextTemplate = (
  id: number,
  payload: {
    templateName: string;
    subjectTemplate?: string;
    titleTemplate?: string;
    contentTemplate: string;
    status?: "ENABLED" | "DISABLED";
  },
) => http.put(`/notification-text-templates/${id}`, payload);
export const enableNotificationTextTemplate = (id: number) => http.post(`/notification-text-templates/${id}/enable`);
export const disableNotificationTextTemplate = (id: number) => http.post(`/notification-text-templates/${id}/disable`);
export const createNotificationPolicy = (payload: {
  policyName: string;
  eventCode: string;
  channel: string;
  receiverType: string;
  templateId: number;
  variablesJson?: string;
  status?: "ENABLED" | "DISABLED";
}) => http.post("/notification-policies", payload);
export const updateNotificationPolicy = (
  id: number,
  payload: {
    policyName: string;
    eventCode: string;
    channel: string;
    receiverType: string;
    templateId: number;
    variablesJson?: string;
    status?: "ENABLED" | "DISABLED";
  },
) => http.put(`/notification-policies/${id}`, payload);
export const bindNotificationPolicyEvents = (id: number, payload: { eventCode: string }) =>
  http.post(`/notification-policies/${id}/events`, payload);
export const enableNotificationPolicy = (id: number) => http.post(`/notification-policies/${id}/enable`);
export const disableNotificationPolicy = (id: number) => http.post(`/notification-policies/${id}/disable`);
export const dispatchNotification = (payload: {
  idempotencyKey: string;
  eventCode: string;
  bizType?: string;
  bizId?: string;
  variablesJson?: string;
  policyId?: number;
}) => http.post("/notifications/dispatch", payload);
export const fetchNotificationTasks = (params?: { pageNo?: number; pageSize?: number }) =>
  http.get("/notifications/tasks", { params });
export const ingestNotificationReceipt = (payload: {
  taskId: number;
  providerMessageId: string;
  receiptCode: string;
  receiptMessage?: string;
  delivered?: boolean;
}) => http.post("/notifications/receipts", payload);
export const fetchInAppNotifications = (params?: { ts?: number }) => http.get("/in-app-notifications", { params });
export const markInAppNotificationRead = (id: number) => http.post(`/in-app-notifications/${id}/read`);
export const markAllInAppNotificationsRead = () => http.post("/in-app-notifications/read-all");
export const fetchExportTasks = () => http.get("/export-tasks");
export const createExportTask = (payload: {
  idempotencyKey: string;
  taskCode: string;
  bizType: string;
  bizId?: string;
  filtersJson?: string;
  fileName?: string;
}) => http.post("/export-tasks", payload);
export const refreshExportTaskToken = (id: number) => http.post(`/export-tasks/${id}/refresh-token`);
export const downloadExportTask = (id: number, params: { token: string }) =>
  http.get(`/export-tasks/${id}/download`, { params });
export const fetchOperationsDashboard = () => http.get("/operations/dashboard");

export const fetchObservabilityMetrics = (params: { metricCode: string; minutes?: number }) =>
  http.get("/observability/metrics", { params });
export const fetchObservabilityExportMetrics = (params?: { minutes?: number }) =>
  http.get("/observability/metrics/export", { params });
export const fetchAlertRules = () => http.get("/observability/alert-rules");
export const createAlertRule = (payload: {
  ruleCode: string;
  ruleName: string;
  compareOp: string;
  thresholdValue: number;
  windowMinute: number;
  suppressWindowMinute?: number;
  status?: "ENABLED" | "DISABLED";
}) => http.post("/observability/alert-rules", payload);
export const updateAlertRule = (
  id: number,
  payload: {
    ruleCode: string;
    ruleName: string;
    compareOp: string;
    thresholdValue: number;
    windowMinute: number;
    suppressWindowMinute?: number;
    status?: "ENABLED" | "DISABLED";
  },
) => http.put(`/observability/alert-rules/${id}`, payload);
export const evaluateAlertRules = () => http.post("/observability/alert-rules/evaluate");
export const evaluateAlertRulesAuto = (params?: { recoveryWindowMinute?: number }) =>
  http.post("/observability/alert-rules/evaluate/auto", null, { params });
export const fetchAlertEvents = () => http.get("/observability/alert-events");

// ========== Phase Zero: Dashboard Stats ==========
export const fetchDashboardStats = () => http.get("/dashboard/stats");

// ========== Phase Zero: Soft Delete & Lifecycle ==========
export const deleteAuditFlow = (id: number) => http.post(`/audit-flows/${id}/delete`);
export const deleteNotificationPolicy = (id: number) => http.post(`/notification-policies/${id}/delete`);
export const deleteNotificationTextTemplate = (id: number) => http.post(`/notification-text-templates/${id}/delete`);

// ========== Phase Zero: Platform User Update ==========
export const updatePlatformUser = (
  id: number,
  payload: {
    userName: string;
    phone: string;
    email?: string;
    validFrom?: string;
    validTo?: string;
    password?: string;
  },
) => http.put(`/platform/users/${id}`, payload);

// ========== Phase Zero: Data Export ==========
export const exportMeetings = (payload: {
  idempotencyKey: string;
  filtersJson?: string;
  fileName?: string;
}) => http.post("/meetings/export", payload);
export const exportUsers = (payload: {
  idempotencyKey: string;
  fileName?: string;
}) => http.post("/users/export", payload);
export const exportProjects = (payload: {
  idempotencyKey: string;
  fileName?: string;
}) => http.post("/projects/export", payload);

// ========== Phase Zero: Tenant Dictionary ==========
export const createDictionary = (payload: {
  dictType: string;
  dictCode: string;
  dictName: string;
  sortNo: number;
  remark?: string;
}) => http.post("/dictionaries", payload);
export const updateDictionary = (
  id: number,
  payload: { dictName: string; sortNo: number; status: "ENABLED" | "DISABLED"; remark?: string },
) => http.put(`/dictionaries/${id}`, payload);
export const enableDictionary = (id: number) => http.post(`/dictionaries/${id}/enable`);
export const disableDictionary = (id: number) => http.post(`/dictionaries/${id}/disable`);
