export interface User { email: string; name: string; subscription: boolean; } const API_BASE = import.meta.env.PUBLIC_API_URL; export const AUTH_TOKEN_KEY = 'authToken' export const USER_KEY = 'user' class BlauwasserAPI { private async fetchAPI( endpoint: string, options: RequestInit = {} ): Promise { const url = new URL(endpoint, API_BASE); const defaultHeaders: HeadersInit = { 'Content-Type': 'application/json', }; if (typeof window !== 'undefined') { const jwt = localStorage.getItem(AUTH_TOKEN_KEY); if (jwt) { defaultHeaders['Authorization'] = `Bearer ${jwt}`; } } const response = await fetch(url, { ...options, headers: { ...defaultHeaders, ...options.headers }, }); if (!response.ok) { throw new Error(`API Error ${response.status}: ${response.statusText}`); } return response.json(); } async getUserInfo(): Promise { return this.fetchAPI(`/users/me`); } async register(user: User): Promise { return this.fetchAPI(`/users`, { method: 'POST', body: JSON.stringify(user) }) } async login(userCode: string): Promise { const formData = new URLSearchParams(); formData.append('user_code', userCode); return await this.fetchAPI('/users/login', { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded', }, body: formData, }); } async toggleSubscription(subscription: boolean): Promise { const formData = new URLSearchParams(); formData.append('subscription', JSON.stringify(subscription)); return await this.fetchAPI('/users/me/subscription', { method: 'PUT', headers: { 'Content-Type': 'application/x-www-form-urlencoded', }, body: formData, }); } async deleteUser(): Promise { return await this.fetchAPI('/users/me', { method: "DELETE" }) } async approveNewsletter(secret: string): Promise { const formData = new URLSearchParams(); formData.append('secret', JSON.stringify(secret)); return await this.fetchAPI('/newsletter/approve', { method: 'POST', body: formData }) } } export const api = new BlauwasserAPI();