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

// --- Types ---

export interface Diagnosis {
  id: string;
  patient_id: string;
  health_record_id?: string;
  icd_code: string;
  diagnosis_name: string;
  diagnosis_type: string;
  diagnosed_date: string;
  status: string;
  diagnosed_by?: string;
  notes?: string;
  created_at: string;
  updated_at: string;
  version: number;
}

export interface CreateDiagnosisReq {
  icd_code: string;
  diagnosis_name: string;
  diagnosis_type?: string;
  diagnosed_date: string;
  status?: string;
  health_record_id?: string;
  diagnosed_by?: string;
  notes?: string;
}

export interface UpdateDiagnosisReq {
  icd_code?: string;
  diagnosis_name?: string;
  diagnosis_type?: string;
  diagnosed_date?: string;
  status?: string;
  health_record_id?: string;
  diagnosed_by?: string;
  notes?: string;
}

// --- Constants ---

export const DIAGNOSIS_TYPE_OPTIONS = [
  { label: '主要诊断', value: 'primary' },
  { label: '次要诊断', value: 'secondary' },
  { label: '合并症', value: 'comorbid' },
];

export const DIAGNOSIS_STATUS_OPTIONS = [
  { label: '活跃', value: 'active' },
  { label: '已缓解', value: 'resolved' },
  { label: '慢性', value: 'chronic' },
];

export const DIAGNOSIS_TYPE_COLOR: Record<string, string> = {
  primary: 'red',
  secondary: 'blue',
  comorbid: 'orange',
};

export const DIAGNOSIS_STATUS_COLOR: Record<string, string> = {
  active: 'green',
  resolved: 'default',
  chronic: 'orange',
};

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

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

// --- API ---

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

  create: async (patientId: string, req: CreateDiagnosisReq) => {
    const { data } = await client.post<{
      success: boolean;
      data: Diagnosis;
    }>(`/health/patients/${patientId}/diagnoses`, req);
    return data.data;
  },

  update: async (diagnosisId: string, req: UpdateDiagnosisReq & { version: number }) => {
    const { data } = await client.put<{
      success: boolean;
      data: Diagnosis;
    }>(`/health/diagnoses/${diagnosisId}`, req);
    return data.data;
  },

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