import { csrfCookieName, csrfCookieOptions } from './csrf-cookie';

describe('csrf-cookie', () => {
  const originalNodeEnv = process.env['NODE_ENV'];
  afterEach(() => {
    if (originalNodeEnv === undefined) {
      delete process.env['NODE_ENV'];
    } else {
      process.env['NODE_ENV'] = originalNodeEnv;
    }
  });

  describe('csrfCookieName', () => {
    it('uses __Host-portal_csrf in production', () => {
      process.env['NODE_ENV'] = 'production';
      expect(csrfCookieName()).toBe('__Host-portal_csrf');
    });

    it('uses portal_csrf in development (HTTP, no Secure)', () => {
      process.env['NODE_ENV'] = 'development';
      expect(csrfCookieName()).toBe('portal_csrf');
    });
  });

  describe('csrfCookieOptions', () => {
    it('is NOT HttpOnly (SPA must read the value to echo it back)', () => {
      expect(csrfCookieOptions(1800_000).httpOnly).toBe(false);
    });

    it('uses SameSite=Lax to travel with the session cookie', () => {
      expect(csrfCookieOptions(1800_000).sameSite).toBe('lax');
    });

    it('sets Secure only in production', () => {
      process.env['NODE_ENV'] = 'production';
      expect(csrfCookieOptions(1800_000).secure).toBe(true);
      process.env['NODE_ENV'] = 'development';
      expect(csrfCookieOptions(1800_000).secure).toBe(false);
    });

    it('pins path=/', () => {
      expect(csrfCookieOptions(1800_000).path).toBe('/');
    });

    it('passes maxAge through unchanged', () => {
      expect(csrfCookieOptions(123456).maxAge).toBe(123456);
    });
  });
});
