import { apiFetch } from '../../services/api';
import type { AuthUser } from '../../services/auth';
import type { APIDiagnosis, APIHospitalVisit, APIPrescription } from '../../services/medical';

export interface APIDiseaseLookup {
    _id: string;
    icdCode: string;
    name: string;
    bodyRegion: string;
    description: string;
}

export function fetchUsersByIds(ids: string[]): Promise<AuthUser[]> {
    return apiFetch('/users/batch', {
        method: 'POST',
        body: JSON.stringify({ ids }),
    });
}

export function fetchPractitionerVisits(
    startDate?: string,
    endDate?: string
): Promise<APIHospitalVisit[]> {
    const params = new URLSearchParams();
    if (startDate) params.set('startDate', startDate);
    if (endDate) params.set('endDate', endDate);
    const qs = params.toString();
    return apiFetch(`/hospital-visits/by-practitioner${qs ? `?${qs}` : ''}`);
}

export function updateSharingInfo(userId: string, sharingInfo: string[]): Promise<AuthUser> {
    return apiFetch(`/users/${userId}`, {
        method: 'PATCH',
        body: JSON.stringify({ sharingInfo }),
    });
}

export function createDiagnosis(payload: {
    patientId: string;
    practitioner: string;
    icdCode: string;
    severity: string;
    hospital: string;
    diagnosisDate: string;
    notes?: string;
}): Promise<APIDiagnosis> {
    return apiFetch('/diagnoses', {
        method: 'POST',
        body: JSON.stringify(payload),
    });
}

export function createPrescription(payload: {
    prescriptionId: string;
    patientId: string;
    medicationId: string;
    dosage: string;
    frequency: string;
    startDate: string;
    endDate: string;
    diagnosisId?: string;
}): Promise<APIPrescription> {
    return apiFetch('/prescriptions', {
        method: 'POST',
        body: JSON.stringify(payload),
    });
}

export function createHospitalVisit(payload: {
    patientId: string;
    hospital: string;
    visitDate: string;
    doctorName?: string;
    department?: string;
    dischargeSummary?: string;
    diagnoses?: string[];
}): Promise<APIHospitalVisit> {
    return apiFetch('/hospital-visits', {
        method: 'POST',
        body: JSON.stringify(payload),
    });
}

export function searchDiseases(query: string): Promise<APIDiseaseLookup[]> {
    return apiFetch(`/diseases?search=${encodeURIComponent(query)}`);
}
