import client from '../client';

// --- Types ---

export interface CriticalValueThreshold {
  id: string;
  tenant_id: string;
  indicator: string;
  direction: string;
  threshold_value: number;
  level: string;
  department?: string;
  age_min?: number;
  age_max?: number;
  is_active: boolean;
  created_at: string;
  updated_at: string;
  version: number;
}

export interface CreateThresholdReq {
  indicator: string;
  direction: string;
  threshold_value: number;
  level?: string;
  department?: string;
  age_min?: number;
  age_max?: number;
}

export interface UpdateThresholdReq {
  threshold_value: number;
  level?: string;
  department?: string;
  age_min?: number;
  age_max?: number;
  version: number;
}

// --- Constants ---

export const INDICATOR_OPTIONS = [
  { label: '收缩压', value: 'systolic_bp' },
  { label: '舒张压', value: 'diastolic_bp' },
  { label: '心率', value: 'heart_rate' },
  { label: '血糖', value: 'blood_sugar' },
  { label: '空腹血糖', value: 'blood_sugar_fasting' },
  { label: '餐后血糖', value: 'blood_sugar_postprandial' },
  { label: '血氧', value: 'blood_oxygen' },
  { label: '体温', value: 'temperature' },
];

export const DIRECTION_OPTIONS = [
  { label: '偏高', value: 'high' },
  { label: '偏低', value: 'low' },
];

export const LEVEL_OPTIONS = [
  { label: '危急', value: 'critical' },
  { label: '警告', value: 'warning' },
];

export const LEVEL_COLOR: Record<string, string> = {
  critical: 'red',
  warning: 'orange',
};

export const INDICATOR_LABEL: Record<string, string> = Object.fromEntries(
  INDICATOR_OPTIONS.map((o) => [o.value, o.label]),
);

export const DIRECTION_LABEL: Record<string, string> = Object.fromEntries(
  DIRECTION_OPTIONS.map((o) => [o.value, o.label]),
);

export const LEVEL_LABEL: Record<string, string> = Object.fromEntries(
  LEVEL_OPTIONS.map((o) => [o.value, o.label]),
);

// --- API ---

export const criticalValueThresholdApi = {
  list: async () => {
    const { data } = await client.get<{
      success: boolean;
      data: CriticalValueThreshold[];
    }>('/health/critical-value-thresholds');
    return data.data;
  },

  create: async (req: CreateThresholdReq) => {
    const { data } = await client.post<{
      success: boolean;
      data: CriticalValueThreshold;
    }>('/health/critical-value-thresholds', req);
    return data.data;
  },

  update: async (id: string, req: UpdateThresholdReq) => {
    const { data } = await client.put<{
      success: boolean;
      data: CriticalValueThreshold;
    }>(`/health/critical-value-thresholds/${id}`, req);
    return data.data;
  },

  delete: async (id: string) => {
    await client.delete(`/health/critical-value-thresholds/${id}`);
  },
};
