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

// --- Types ---

export interface Consent {
  id: string;
  patient_id: string;
  consent_type: string;
  consent_scope: string;
  status: string;
  granted_at?: string;
  revoked_at?: string;
  expiry_date?: string;
  consent_method?: string;
  witness_name?: string;
  notes?: string;
  created_at: string;
  updated_at: string;
  version: number;
}

export interface CreateConsentReq {
  patient_id: string;
  consent_type: string;
  consent_scope: string;
  expiry_date?: string;
  consent_method?: string;
  witness_name?: string;
  notes?: string;
}

export interface RevokeConsentReq {
  notes?: string;
  version: number;
}

// --- Constants ---

export const CONSENT_TYPE_OPTIONS = [
  { label: '治疗同意', value: 'treatment' },
  { label: '数据共享', value: 'data_sharing' },
  { label: '隐私政策', value: 'privacy' },
  { label: '研究参与', value: 'research' },
];

export const CONSENT_SCOPE_OPTIONS = [
  { label: '全部', value: 'all' },
  { label: '健康数据', value: 'health_data' },
  { label: '基本信息', value: 'basic_info' },
  { label: '体检报告', value: 'examination' },
];

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

export const CONSENT_STATUS_LABEL: Record<string, string> = {
  active: '生效中',
  revoked: '已撤销',
  expired: '已过期',
};

// --- API ---

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

  grant: async (req: CreateConsentReq) => {
    const { data } = await client.post<{
      success: boolean;
      data: Consent;
    }>('/health/consents', req);
    return data.data;
  },

  revoke: async (consentId: string, req: RevokeConsentReq) => {
    const { data } = await client.put<{
      success: boolean;
      data: Consent;
    }>(`/health/consents/${consentId}/revoke`, req);
    return data.data;
  },
};
