// pwa/assets/js/pwa_auth.js
// Minimal PWA auth helper. Uses localStorage for tokens and provides a fetch wrapper.

const PWA_AUTH = (() => {
  const LS_KEY = 'atulyasolar_auth';

  function saveAuth(payload) {
    const toSave = {
      team_id: payload.team_id,
      role: payload.role,
      name: payload.name,
      pwa_token: payload.pwa_token,
      pwa_token_expiry: payload.pwa_token_expiry,
      login_token: payload.login_token,
      login_token_expiry: payload.login_token_expiry
    };
    localStorage.setItem(LS_KEY, JSON.stringify(toSave));
  }

  function getAuth() {
    const raw = localStorage.getItem(LS_KEY);
    if (!raw) return null;
    try {
      return JSON.parse(raw);
    } catch (e) {
      localStorage.removeItem(LS_KEY);
      return null;
    }
  }

  async function login(identifier, password) {
    const resp = await fetch('/api/auth/login.php', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ identifier, password })
    });
    const j = await resp.json();
    if (resp.ok && j.success) {
      saveAuth(j.data);
      return { success: true, data: j.data };
    } else {
      return { success: false, error: j };
    }
  }

  function logout() {
    localStorage.removeItem(LS_KEY);
    // optionally call server logout endpoint if implemented
  }

  function getAuthToken() {
    const a = getAuth();
    if (!a) return null;
    // prefer pwa_token for long-lived sessions
    return a.pwa_token || a.login_token || null;
  }

  // Fetch wrapper that adds Authorization header
  async function apiFetch(path, opts = {}) {
    opts.headers = opts.headers || {};
    const token = getAuthToken();
    if (token) {
      opts.headers['Authorization'] = 'Bearer ' + token;
    }
    opts.credentials = opts.credentials || 'same-origin';
    const res = await fetch(path, opts);
    // handle 401 centrally
    if (res.status === 401) {
      // clear auth and redirect to login
      logout();
      // Optionally: window.location = '/pwa/login.html';
      throw new Error('Unauthorized - session expired');
    }
    return res;
  }

  return {
    login,
    logout,
    getAuth,
    apiFetch
  };
})();
