import client from '../client';
import type { PaginatedResponse } from '../types';

// --- Types ---

export interface MedicationRecord {
  id: string;
  patient_id: string;
  medication_name: string;
  generic_name?: string;
  dosage?: string;
  unit?: string;
  frequency?: string;
  route?: string;
  start_date?: string;
  end_date?: string;
  is_current: boolean;
  prescribed_by?: string;
  notes?: string;
  created_at: string;
  updated_at: string;
  version: number;
}

export interface CreateMedicationRecordReq {
  patient_id: string;
  medication_name: string;
  generic_name?: string;
  dosage?: string;
  unit?: string;
  frequency?: string;
  route?: string;
  start_date?: string;
  end_date?: string;
  is_current?: boolean;
  prescribed_by?: string;
  notes?: string;
}

export interface UpdateMedicationRecordReq {
  medication_name?: string;
  generic_name?: string;
  dosage?: string;
  unit?: string;
  frequency?: string;
  route?: string;
  start_date?: string;
  end_date?: string;
  is_current?: boolean;
  prescribed_by?: string;
  notes?: string;
}

// --- Constants ---

export const FREQUENCY_OPTIONS = [
  { label: '每日一次', value: 'QD' },
  { label: '每日两次', value: 'BID' },
  { label: '每日三次', value: 'TID' },
  { label: '每晚一次', value: 'QN' },
  { label: '每周一次', value: 'QW' },
  { label: '必要时', value: 'PRN' },
];

export const ROUTE_OPTIONS = [
  { label: '口服', value: 'oral' },
  { label: '静脉注射', value: 'iv' },
  { label: '皮下注射', value: 'sc' },
  { label: '外用', value: 'topical' },
  { label: '吸入', value: 'inhalation' },
];

// --- API ---

export const medicationRecordApi = {
  list: async (patientId: string, params?: { page?: number; page_size?: number }) => {
    const { data } = await client.get<{
      success: boolean;
      data: PaginatedResponse<MedicationRecord>;
    }>(`/health/patients/${patientId}/medications`, { params });
    return data.data;
  },

  get: async (id: string) => {
    const { data } = await client.get<{
      success: boolean;
      data: MedicationRecord;
    }>(`/health/medications/${id}`);
    return data.data;
  },

  create: async (req: CreateMedicationRecordReq) => {
    const { data } = await client.post<{
      success: boolean;
      data: MedicationRecord;
    }>('/health/medications', req);
    return data.data;
  },

  update: async (id: string, req: UpdateMedicationRecordReq & { version: number }) => {
    const { data } = await client.put<{
      success: boolean;
      data: MedicationRecord;
    }>(`/health/medications/${id}`, req);
    return data.data;
  },

  delete: async (id: string, version: number) => {
    await client.delete(`/health/medications/${id}`, { data: { version } });
  },
};
