// BizGaze as identity provider.
// Validates a username/password against BizGaze's ValidateAndLogin endpoint.
// Enabled only when BIZGAZE_LOGIN_URL is set (so tests/local runs stay self-contained).
//
// Success response shape (observed):
//   { status: 1, currentSession: { name, userId, tenantId, unibaseId, isAdmin, ... }, message }
// Failure: status !== 1, with a `message`.

function loginUrl() { return process.env.BIZGAZE_LOGIN_URL || ''; }
const isEnabled = () => !!loginUrl();

// Origin of the BizGaze app (e.g. https://c02.bizgaze.app), derived from the login URL.
function loginOrigin() { try { return new URL(loginUrl()).origin; } catch { return ''; } }

// Build an absolute profile-photo URL from the session payload. BizGaze returns a
// relative path like "_files/documents/.../x.jpg" plus an asset/app base; we try the
// asset host first, then the app host, then the login origin. Absolute URLs pass through.
function photoUrlFrom(s) {
  const raw = s.photoUrl || s.PhotoUrl || s.photo || s.profilePic || s.imageUrl || '';
  if (!raw || typeof raw !== 'string') return null;
  if (/^https?:\/\//i.test(raw)) return raw;
  const base = String(s.assetUrl || s.appUrl || loginOrigin() || '').replace(/\/+$/, '');
  return base ? base + '/' + raw.replace(/^\/+/, '') : null;
}

async function validateLogin(username, password) {
  const url = loginUrl();
  if (!url) return { ok: false, configured: false };
  let res;
  try {
    res = await fetch(url, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ UserName: username, Password: password, UnibaseId: '', RememberMe: false }),
      signal: AbortSignal.timeout(15000),
    });
  } catch (e) {
    return { ok: false, configured: true, error: 'BizGaze sign-in is unavailable right now' };
  }
  let data;
  try { data = await res.json(); } catch { return { ok: false, configured: true, error: 'Unexpected response from BizGaze' }; }
  const s = data && data.currentSession;
  if (data && data.status === 1 && s) {
    return {
      ok: true, configured: true,
      name: s.name || null,
      avatarUrl: photoUrlFrom(s),
      isAdmin: !!s.isAdmin,
      tenantRef: s.tenantId != null ? String(s.tenantId) : null,  // BizGaze tenant (org) id
      bizgazeUserId: s.userId != null ? String(s.userId) : null,
      unibaseId: s.unibaseId || null,
      message: data.message || 'Login Success',
    };
  }
  return { ok: false, configured: true, message: (data && data.message) || 'Invalid BizGaze credentials' };
}

module.exports = { validateLogin, isEnabled };
