import client from '../client';

// --- Types ---

export interface FamilyMember {
  id: string;
  patient_id: string;
  name: string;
  relationship: string;
  phone?: string;
  birth_date?: string;
  notes?: string;
  user_id?: string;
  consent_status: string;
  access_level: string;
  consented_at?: string;
  created_at: string;
  updated_at: string;
  version: number;
}

export interface FamilyPatientSummary {
  family_member_id: string;
  patient_id: string;
  patient_name: string;
  relationship: string;
  consent_status: string;
  access_level: string;
  consented_at?: string;
}

export interface FamilyHealthSummary {
  patient_id: string;
  patient_name: string;
  latest_vital_signs?: Record<string, unknown>;
  active_care_plan?: Record<string, unknown>;
  recent_alerts_count: number;
  next_appointment?: Record<string, unknown>;
}

export interface GrantAccessReq {
  access_level: string;
}

// --- Constants ---

export const CONSENT_STATUS_OPTIONS = [
  { label: '已同意', value: 'granted' },
  { label: '待确认', value: 'pending' },
  { label: '已撤销', value: 'revoked' },
  { label: '已过期', value: 'expired' },
];

export const ACCESS_LEVEL_OPTIONS = [
  { label: '完全访问', value: 'full' },
  { label: '只读', value: 'read_only' },
  { label: '摘要', value: 'summary' },
];

export const CONSENT_STATUS_COLOR: Record<string, string> = {
  granted: 'green',
  pending: 'orange',
  revoked: 'red',
  expired: 'default',
};

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

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

// --- API ---

export const familyProxyApi = {
  grantAccess: async (patientId: string, familyMemberId: string, req: GrantAccessReq, version: number) => {
    const { data } = await client.post<{
      success: boolean;
      data: FamilyMember;
    }>(`/health/patients/${patientId}/family-members/${familyMemberId}/grant-access`, { ...req, version });
    return data.data;
  },

  revokeAccess: async (patientId: string, familyMemberId: string, version: number) => {
    const { data } = await client.put<{
      success: boolean;
      data: FamilyMember;
    }>(`/health/patients/${patientId}/family-members/${familyMemberId}/revoke-access`, { version });
    return data.data;
  },

  listMyPatients: async () => {
    const { data } = await client.get<{
      success: boolean;
      data: FamilyPatientSummary[];
    }>('/health/family/patients');
    return data.data;
  },

  getHealthSummary: async (patientId: string) => {
    const { data } = await client.get<{
      success: boolean;
      data: FamilyHealthSummary;
    }>(`/health/family/patients/${patientId}/health-summary`);
    return data.data;
  },
};
