import { writable, get } from 'svelte/store';
import { base } from './basestore';

export const dossierData = writable<Dossier>({} as Dossier);
export const dossierDataDownloadsInProgress = writable<number>(0);
export const loading = writable(false);
export const error = writable<string | null>(null);


const headers = new Headers({
    'Content-Type': 'application/json',
    'Accept-Encoding': 'gzip',
    'X-CSRF': '1', // Required header for BFF middleware
    // Add Authorization token if required
    // 'Authorization': `Bearer ${yourToken}`
});

export async function fetchPatientDossier() {
    loading.set(true);
    error.set(null);

    try {
        const baseUrl = get(base);
        const response = await fetch(`${baseUrl}api/resources/dossier`, { method: 'GET', headers });

        if (!response.ok) {
            throw new Error(`Error: ${response.status} - ${response.statusText}`);
        }

        const data: Dossier = await response.json();
        dossierData.set(data);
    } catch (err: any) {
        error.set(err.message || 'An unknown error occurred');
    } finally {
        loading.set(false);
    }
}

export async function fetchStatusDownloadsInProgress() {
    try {
        const response = await fetch(`${get(base)}api/import/status`, { method: 'GET', headers });
        dossierDataDownloadsInProgress.set((await response.json())?.downloadsInProgress);
    } catch (err: any) {
        dossierDataDownloadsInProgress.set(-1);
    }
}

export async function resetDownloads() {
    try {
        await fetch(`${get(base)}api/import/reset`, { method: 'GET', headers });
        await fetchPatientDossier();
    } catch (err: any) {
        console.error(err);
    }
}


export interface Dossier {
    patients: Patient[];
    allergyIntolerances: AllergyIntolerance[];
    carePlans: CarePlan[];
    careTeams: CareTeam[];
    compositions: Composition[];
    conditions: Condition[];
    diagnosticReports: DiagnosticReport[];
    documentManifests: DocumentManifest[];
    documentReferences: DocumentReference[];
    episodesOfCare: EpisodeOfCare[];
    encounters: Encounter[];
    flags: Flag[];
    goals: Goal[];
    immunizations: Immunization[];
    medications: Medication[];
    medicationAdministrations: MedicationAdministration[];
    medicationDispenses: MedicationDispense[];
    medicationRequests: MedicationRequest[];
    medicationStatements: MedicationStatement[];
    observations: Observation[];
    organizations: Organization[];
    practitioners: Practitioner[];
    procedures: Procedure[];
    questionnaireResponses: QuestionnaireResponse[];
    others: OtherUnmapped[];
}

export interface Patient {
    id: string;
    resourceType: string;
    name?: string;
    gender?: string;
    birthDate?: string;
    addressLine?: string;
    city?: string;
    postalCode?: string;
    country?: string;
}

export interface AllergyIntolerance {
    id: string;
    resourceType: string;
    clinicalStatus?: string;
    verificationStatus?: string;
}

export interface CarePlan {
    id: string;
    resourceType: string;
    status?: string;
    intent?: string;
}

export interface CareTeam {
    id: string;
    resourceType: string;
    status?: string;
}

export interface Composition {
    id: string;
    resourceType: string;
    status?: string;
    author?: string;
    title?: string;
    subjectief?: string;
    objectief?: string;
    evaluatie?: string;
    plan?: string;
}

export interface Condition {
    id: string;
    resourceType: string;
    clinicalStatus?: string;
    verificationStatus?: string;
}

export interface DiagnosticReport {
    id: string;
    resourceType: string;
    status?: string;
    code?: string;
}

export interface DocumentManifest {
    id: string;
    resourceType: string;
    status?: string;
}

export interface DocumentReference {
    id: string;
    resourceType: string;
    status?: string;
    author?: string;
    custodian?: string;
    content?: string;
    code?: string;
    period?: string;

    source?: string;
    title?: string;
    contentType?: string;
    

}

export interface EpisodeOfCare {
    id: string;
    resourceType: string;
    status?: string;
    diagnosis: string[];
    managingOrganization?: string;
    period?: string;
    careManager?: string;
}

export interface Encounter {
    id: string;
    resourceType: string;
    status?: string;
}

export interface Flag {
    id: string;
    resourceType: string;
    status?: string;
}

export interface Goal {
    id: string;
    resourceType: string;
    status?: string;
}

export interface Immunization {
    id: string;
    resourceType: string;
    status?: string;
}

export interface Medication {
    id: string;
    resourceType: string;
    status?: string;
}

export interface MedicationAdministration {
    id: string;
    resourceType: string;
    status?: string;
}

export interface MedicationDispense {
    id: string;
    resourceType: string;
    status?: string;
}

export interface MedicationRequest {
    id: string;
    resourceType: string;
    status?: string;
    requester?: string;
    dosageInstruction?: string;
}

export interface MedicationStatement {
    id: string;
    resourceType: string;
    status?: string;
}

export interface Observation {
    id: string;
    resourceType: string;
    status?: string;
    code?: string;
}

export interface Organization {
    id: string;
    resourceType: string;
    name: string;
}

export interface Practitioner {
    id: string;
    resourceType: string;
    name?: string;
}

export interface Procedure {
    id: string;
    resourceType: string;
    status?: string;
    code?: string;
}

export interface QuestionnaireResponse {
    id: string;
    resourceType: string;
    status?: string;
}

export interface OtherUnmapped {
    id: string;
    resourceType: string;
}


const dossierStore = writable<Dossier>({
    patients: [],
    allergyIntolerances: [],
    carePlans: [],
    careTeams: [],
    compositions: [],
    conditions: [],
    diagnosticReports: [],
    documentManifests: [],
    documentReferences: [],
    episodesOfCare: [],
    encounters: [],
    flags: [],
    goals: [],
    immunizations: [],
    medications: [],
    medicationAdministrations: [],
    medicationDispenses: [],
    medicationRequests: [],
    medicationStatements: [],
    observations: [],
    organizations: [],
    practitioners: [],
    procedures: [],
    questionnaireResponses: [],
    others: []
});
