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

// --- Types ---
export interface DeviceReading {
  id: string;
  device_id?: string;
  device_type: string;
  device_model?: string;
  raw_value: Record<string, unknown>;
  measured_at: string;
  created_at: string;
}

export interface HourlyReading {
  id: string;
  device_type: string;
  hour_start: string;
  min_val?: number;
  max_val?: number;
  avg_val: number;
  sample_count: number;
}

export interface DailyReading {
  id: string;
  device_type: string;
  date_bucket: string;
  min_val?: number;
  max_val?: number;
  avg_val: number;
  sample_count: number;
  percentile_95?: number;
}

export interface BatchReadingRequest {
  device_id: string;
  device_model?: string;
  readings: {
    device_type: string;
    values: Record<string, unknown>;
    measured_at: string;
  }[];
}

export interface BatchResult {
  accepted: number;
  duplicates: number;
  earliest?: string;
  latest?: string;
}

// --- API ---
export const deviceReadingApi = {
  batchCreate: (patientId: string, data: BatchReadingRequest) =>
    client.post(`/health/patients/${patientId}/device-readings/batch`, data).then((r) => r.data.data as BatchResult),

  query: (params: { patient_id: string; device_type?: string; hours?: number; page?: number; page_size?: number }) => {
    const { patient_id, ...query } = params;
    return client.get(`/health/patients/${patient_id}/device-readings`, { params: query }).then((r) => r.data.data as PaginatedResponse<DeviceReading>);
  },

  queryHourly: (params: { patient_id: string; device_type: string; days?: number; page?: number; page_size?: number }) => {
    const { patient_id, ...query } = params;
    return client.get(`/health/patients/${patient_id}/device-readings/hourly`, { params: query }).then((r) => r.data.data as PaginatedResponse<HourlyReading>);
  },

  queryDaily: (params: { patient_id: string; device_type?: string; from_date?: string; to_date?: string; page?: number; page_size?: number }) => {
    const { patient_id, ...query } = params;
    return client.get(`/health/vital-signs/daily`, { params: { ...query, patient_id } }).then((r) => r.data.data as PaginatedResponse<DailyReading>);
  },
};
