File size: 4,838 Bytes
c024705
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
/**
 * AIMHSA API Client
 * Centralized API communication with automatic configuration
 */

class ApiClient {
    constructor() {
        this.config = window.AppConfig;
        this.defaultHeaders = {
            'Content-Type': 'application/json'
        };
    }
    
    async request(endpoint, options = {}) {
        const url = this.config.getFullUrl(endpoint);
        
        const defaultOptions = {
            method: 'GET',
            headers: { ...this.defaultHeaders },
            timeout: this.config.settings.defaultTimeout
        };
        
        const mergedOptions = { ...defaultOptions, ...options };
        
        // Add custom headers if provided
        if (options.headers) {
            mergedOptions.headers = { ...mergedOptions.headers, ...options.headers };
        }
        
        try {
            const response = await fetch(url, mergedOptions);
            
            if (!response.ok) {
                throw new Error(`HTTP ${response.status}: ${response.statusText}`);
            }
            
            const contentType = response.headers.get('content-type');
            if (contentType && contentType.includes('application/json')) {
                return await response.json();
            } else {
                return await response.text();
            }
        } catch (error) {
            console.error('API Request failed:', error);
            throw error;
        }
    }
    
    // GET request
    async get(endpoint, params = {}) {
        const url = new URL(this.config.getFullUrl(endpoint), window.location.origin);
        Object.keys(params).forEach(key => {
            if (params[key] !== null && params[key] !== undefined) {
                url.searchParams.append(key, params[key]);
            }
        });
        
        return await fetch(url.toString(), {
            method: 'GET',
            headers: this.defaultHeaders
        }).then(res => res.json());
    }
    
    // POST request
    async post(endpoint, data = {}, options = {}) {
        return await this.request(endpoint, {
            method: 'POST',
            body: JSON.stringify(data),
            ...options
        });
    }
    
    // PUT request
    async put(endpoint, data = {}, options = {}) {
        return await this.request(endpoint, {
            method: 'PUT',
            body: JSON.stringify(data),
            ...options
        });
    }
    
    // DELETE request
    async delete(endpoint, options = {}) {
        return await this.request(endpoint, {
            method: 'DELETE',
            ...options
        });
    }
    
    // Chat-specific methods
    async sendMessage(query, conversationId = null, account = null) {
        return await this.post('ask', {
            query,
            id: conversationId,
            account
        });
    }
    
    async getSession(account = null) {
        return await this.post('session', { account });
    }
    
    async getHistory(conversationId, password = null) {
        const params = { id: conversationId };
        if (password) params.password = password;
        return await this.get('history', params);
    }
    
    // Auth methods
    async login(email, password) {
        return await this.post('login', { email, password });
    }
    
    async register(userData) {
        return await this.post('register', userData);
    }
    
    async professionalLogin(credentials) {
        return await this.post('professionalLogin', credentials);
    }
    
    async adminLogin(credentials) {
        return await this.post('adminLogin', credentials);
    }
    
    // Professional methods
    async getProfessionalProfile(professionalId) {
        return await this.get('professionalProfile', {}, {
            headers: { 'X-Professional-ID': professionalId }
        });
    }
    
    async getProfessionalSessions(professionalId, limit = 50) {
        return await this.get('professionalSessions', { limit }, {
            headers: { 'X-Professional-ID': professionalId }
        });
    }
    
    // Health check
    async healthCheck() {
        try {
            const response = await this.get('healthz');
            return response.ok === true;
        } catch (error) {
            return false;
        }
    }
}

// Global API client instance
window.ApiClient = new ApiClient();

// Auto-check API connectivity on load
document.addEventListener('DOMContentLoaded', async () => {
    try {
        const isHealthy = await window.ApiClient.healthCheck();
        if (!isHealthy && window.AppConfig.isDevelopment()) {
            console.warn('⚠️ API health check failed - backend may not be running');
        }
    } catch (error) {
        if (window.AppConfig.isDevelopment()) {
            console.error('❌ Failed to check API health:', error);
        }
    }
});