
// src/api.js
import { state } from './state.js';

export async function login(email, password) {
  try {
    const res = await fetch(`${state.URI}/auth/login`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ email, password })
    });
    if (!res.ok) throw new Error(`HTTP ${res.status}: ${await res.text()}`);
    const data = await res.json();
    return data.token;
  } catch (err) {
    alert(err);
    return null;
  }
}

export async function getLinks(Storage, renderApps, loadAppOrder) {
  try {
    const token = await login(state.USER, state.PASSW);
    if (!token) throw new Error('User o Password errati');
    const res = await fetch(`${state.URI}/links`, {
      headers: { 'Authorization': `Bearer ${token}`, 'Accept': 'application/json' }
    });
    if (!res.ok) throw new Error('Server errato o non risponde');
    const json = await res.json();

    state.appsData = json.map((a, i) => {
      let icon = null;
      if (a.icon && a.icon.data && a.icon.mime) {
        const base64 = btoa(String.fromCharCode(...a.icon.data.data));
        icon = `data:${a.icon.mime};base64,${base64}`;
      }
      return { id: a.id ?? `app-${i}`, name: a.name, url: a.url, icon };
    });

    await Storage.saveApps(state.appsData);
    await loadAppOrder(Storage);
    renderApps();
    return true;
  } catch (err) {
    console.error(err);
    return null;
  }
}
