import type { AdminFormType } from './role-meta';

const UNUSED_ID_FIELDS = [
  'store_id',
  'doctor_id',
  'pharmacist_id',
  'supplier_id',
  'delivery_warehouse_id',
] as const;

function isEmptyId(value: unknown): boolean {
  return value === '' || value === null || value === undefined;
}

function toZeroOrOmit(
  payload: Record<string, unknown>,
  field: string,
  omitWhenEmpty: boolean,
): void {
  if (!(field in payload)) {
    return;
  }
  if (isEmptyId(payload[field])) {
    if (omitWhenEmpty) {
      delete payload[field];
    } else {
      payload[field] = 0;
    }
  }
}

/**
 * 提交前归一化：避免整型列收到 ''；不削弱各角色必填校验（在 validate 之后调用）。
 */
export function normalizeAdminPayload(
  values: Record<string, unknown>,
  formType: AdminFormType,
): Record<string, unknown> {
  const payload = { ...values };
  delete payload.confirmPassword;

  switch (formType) {
    case 'basic':
      for (const field of UNUSED_ID_FIELDS) {
        toZeroOrOmit(payload, field, true);
      }
      break;
    case 'address':
      for (const field of UNUSED_ID_FIELDS) {
        toZeroOrOmit(payload, field, true);
      }
      break;
    case 'supplier':
      toZeroOrOmit(payload, 'store_id', true);
      toZeroOrOmit(payload, 'doctor_id', true);
      toZeroOrOmit(payload, 'pharmacist_id', true);
      toZeroOrOmit(payload, 'delivery_warehouse_id', true);
      break;
    case 'deliveryWarehouse':
      toZeroOrOmit(payload, 'store_id', true);
      toZeroOrOmit(payload, 'doctor_id', true);
      toZeroOrOmit(payload, 'pharmacist_id', true);
      toZeroOrOmit(payload, 'supplier_id', true);
      break;
    case 'clinic':
      toZeroOrOmit(payload, 'doctor_id', true);
      toZeroOrOmit(payload, 'pharmacist_id', true);
      toZeroOrOmit(payload, 'supplier_id', true);
      toZeroOrOmit(payload, 'delivery_warehouse_id', true);
      break;
    case 'doctor':
      toZeroOrOmit(payload, 'pharmacist_id', true);
      toZeroOrOmit(payload, 'supplier_id', true);
      toZeroOrOmit(payload, 'delivery_warehouse_id', true);
      if (isEmptyId(payload.doctor_id)) {
        payload.doctor_id = 0;
      }
      break;
    case 'pharmacist':
      toZeroOrOmit(payload, 'doctor_id', true);
      toZeroOrOmit(payload, 'supplier_id', true);
      toZeroOrOmit(payload, 'delivery_warehouse_id', true);
      if (isEmptyId(payload.pharmacist_id)) {
        payload.pharmacist_id = 0;
      }
      break;
    default:
      break;
  }

  return payload;
}
