// Authentication Middleware Integration Tests

import request from 'supertest';
import app from '@/integration/api-gateway/app';
import { createTestToken } from '@/__tests__/utils/test-auth';

describe('Authentication Middleware', () => {
  describe('zeroTrustAuthMiddleware', () => {
    it('rejects requests without a token', async () => {
      const response = await request(app).get('/api/auth/me').expect(401);

      expect(response.body.success).toBe(false);
      expect(response.body.error.code).toBe('UNAUTHORIZED');
    });

    it('rejects requests with an invalid token', async () => {
      const response = await request(app)
        .get('/api/auth/me')
        .set('authorization', 'SOV-TOKEN invalid-token')
        .expect(401);

      expect(response.body.success).toBe(false);
      expect(response.body.error.code).toBe('UNAUTHORIZED');
    });

    it('accepts a valid portal token without sovereign signature headers', async () => {
      const token = createTestToken({
        employeeId: 'EMP-001',
        email: 'core.ops@d-bis.org',
        name: 'Core Operations User',
        roleName: 'DBIS_Core_User',
        permissions: ['portal:access', 'admin:view'],
        identityType: 'WEB_PORTAL',
        sessionType: 'portal',
        portalSurface: 'core',
        sovereignBankId: undefined,
      });

      const response = await request(app)
        .get('/api/auth/me')
        .set('authorization', `SOV-TOKEN ${token}`)
        .expect(200);

      expect(response.body.user).toMatchObject({
        employeeId: 'EMP-001',
        email: 'core.ops@d-bis.org',
        name: 'Core Operations User',
        role: 'DBIS_Core_User',
        permissions: ['portal:access', 'admin:view'],
      });
    });
  });

  describe('Request Signature Verification', () => {
    it('requires signature headers for service tokens', async () => {
      const token = createTestToken({
        sovereignBankId: 'test-bank',
        identityType: 'API',
        sessionType: 'service',
      });

      const response = await request(app)
        .get('/api/auth/me')
        .set('authorization', `SOV-TOKEN ${token}`)
        .expect(401);

      expect(response.body.error.message).toContain('signature');
    });
  });
});
