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

// ZAL providers
export const providersApd = writable<StelselNodeProvider[]>([]); // Aanbieders in het persoonsdomein (APD, PGO)
export const providersZa = writable<StelselNodeProvider[]>([]); // Aanbieders in het zorgdomein (ZA, DVA)
export const loading = writable(false);
export const error = writable<string | null>(null);



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

    try {
        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}`
        });

        // Aanbieders in het persoonsdomein (APD, PGO)
        const baseUrl = get(base);
        let response = await fetch(`${baseUrl}/api/medmij-register/aanbieders-persoonsdomein`, { method: 'GET', headers});
        if (!response.ok) throw new Error(`Error: ${response.status} - ${response.statusText}`);
        providersApd.set(await response.json());

        // Aanbieders in het zorgdomein (ZA, DVA)
        response = await fetch(`${baseUrl}/api/medmij-register/aanbieders-zorgdomein`, { method: 'GET', headers});
        if (!response.ok) throw new Error(`Error: ${response.status} - ${response.statusText}`);
        providersZa.set(await response.json());

    } catch (err: any) {
        error.set(err.message || 'An unknown error occurred');
    } finally {
        loading.set(false);
    }
}

export interface StelselNodeProvider {
    name: string;
    displayName: string;
    providerType: string; // Unknown, Zorgaanbieder, Basiszorgaanbieder, AanbiederPersoonsdomein
}
