const { getAgent } = require('../testServer');

const DEFAULT_CREDENTIALS = {
  username: 'testadmin',
  password: 'SuperSicher123!'
};

let cachedSession = null;

async function initializeSession() {
  const agent = getAgent();

  const statusResponse = await agent
    .get('/auth/setup/status')
    .expect(200);

  let csrfToken;

  if (statusResponse.body.needsSetup) {
    const setupResponse = await agent
      .post('/auth/setup/initial-admin')
      .send(DEFAULT_CREDENTIALS)
      .expect(201);

    csrfToken = setupResponse.body?.csrfToken;
  } else {
    const loginResponse = await agent
      .post('/auth/login')
      .send(DEFAULT_CREDENTIALS);

    if (loginResponse.status === 409 && loginResponse.body?.error === 'SETUP_REQUIRED') {
      // Edge case: setup status may lag behind – perform setup now
      const setupResponse = await agent
        .post('/auth/setup/initial-admin')
        .send(DEFAULT_CREDENTIALS)
        .expect(201);
      csrfToken = setupResponse.body?.csrfToken;
    } else if (loginResponse.status !== 200) {
      throw new Error(
        `Failed to log in test admin (status ${loginResponse.status}): ${JSON.stringify(loginResponse.body)}`
      );
    } else {
      csrfToken = loginResponse.body?.csrfToken;
    }
  }

  if (!csrfToken) {
    const csrfResponse = await agent.get('/auth/csrf-token').expect(200);
    csrfToken = csrfResponse.body.csrfToken;
  }

  cachedSession = { agent, csrfToken };
  return cachedSession;
}

async function getAdminSession() {
  if (cachedSession) {
    return cachedSession;
  }
  return initializeSession();
}

async function refreshCsrfToken() {
  const session = await getAdminSession();
  const csrfResponse = await session.agent.get('/auth/csrf-token').expect(200);
  session.csrfToken = csrfResponse.body.csrfToken;
  return session.csrfToken;
}

module.exports = {
  getAdminSession,
  refreshCsrfToken
};
