// src/config/passport.test.ts
import { describe, it, expect, vi, beforeEach, type Mocked } from 'vitest';
import * as bcrypt from 'bcrypt';
import { Request, Response, NextFunction } from 'express';

// Define a type for the JWT verify callback function for type safety.
type VerifyCallback = (
  payload: { user_id: string },
  done: (error: Error | null, user?: object | false) => void,
) => Promise<void>;

// FIX: Use vi.hoisted to declare variables that need to be accessed inside vi.mock
const { verifyCallbackWrapper } = vi.hoisted(() => {
  return {
    // We use a wrapper object to hold the callback reference
    // Initialize with a more specific type instead of `any`.
    verifyCallbackWrapper: {
      callback: null as VerifyCallback | null,
    },
  };
});

// Mock the 'passport-jwt' module to capture the verify callback.
vi.mock('passport-jwt', () => ({
  // The Strategy constructor is mocked to capture its second argument
  Strategy: vi.fn(function (options, verify) {
    // FIX: Assign to the hoisted wrapper object
    verifyCallbackWrapper.callback = verify;
    return { name: 'jwt', authenticate: vi.fn() };
  }),
  ExtractJwt: { fromAuthHeaderAsBearerToken: vi.fn() },
}));

// FIX: Add a similar mock for 'passport-local' to capture its verify callback.
const { localStrategyCallbackWrapper } = vi.hoisted(() => {
  type LocalVerifyCallback = (
    req: Request,
    email: string,
    pass: string,
    done: (error: Error | null, user?: object | false, options?: { message: string }) => void,
  ) => Promise<void>;
  return {
    localStrategyCallbackWrapper: { callback: null as LocalVerifyCallback | null },
  };
});

vi.mock('passport-local', () => ({
  Strategy: vi.fn(function (options, verify) {
    localStrategyCallbackWrapper.callback = verify;
  }),
}));

import * as db from '../services/db/index.db';
import { UserProfile } from '../types';
import {
  createMockUserProfile,
  createMockUserWithPasswordHash,
} from '../tests/utils/mockFactories';
import { createMockRequest } from '../tests/utils/createMockRequest';

// Mock dependencies before importing the passport configuration
vi.mock('../services/db/index.db', () => ({
  userRepo: {
    findUserByEmail: vi.fn(),
    findUserWithProfileByEmail: vi.fn(), // ADD THIS
    findUserProfileById: vi.fn(),
  },
  adminRepo: {
    incrementFailedLoginAttempts: vi.fn(),
    resetFailedLoginAttempts: vi.fn(),
    logActivity: vi.fn(),
  },
}));

const mockedDb = db as Mocked<typeof db>;

vi.mock('../services/logger.server', async () => ({
  // Use async import to avoid hoisting issues with mockLogger
  // Note: We need to await the import inside the factory
  logger: (await import('../tests/utils/mockLogger')).mockLogger,
}));

// Mock bcrypt for password comparisons
vi.mock('bcrypt', () => ({
  compare: vi.fn(),
}));

// Mock the passport library
vi.mock('passport', () => {
  const mAuthenticate = vi.fn(() => (req: Request, res: Response, next: NextFunction) => next());
  return {
    // The `passport` module has a default export which is an object containing the methods.
    default: {
      use: vi.fn(),
      initialize: vi.fn(() => (req: Request, res: Response, next: NextFunction) => next()),
      authenticate: mAuthenticate,
    },
    // It also has named exports, so we mock `authenticate` here as well for completeness.
    authenticate: mAuthenticate,
  };
});

// Now, import the passport configuration which will use our mocks
import passport, { isAdmin, optionalAuth, mockAuth } from './passport';
import { logger } from '../services/logger.server';
import { ForbiddenError } from '../services/db/errors.db';

describe('Passport Configuration', () => {
  beforeEach(() => {
    vi.clearAllMocks();
    vi.resetModules();
  });

  describe('LocalStrategy (Isolated Callback Logic)', () => {
    // FIX: mockReq needs a 'log' property because the implementation uses req.log
    const mockReq = createMockRequest({ ip: '127.0.0.1' });
    const done = vi.fn();

    it('should call done(null, user) on successful authentication', async () => {
      // Arrange
      const mockAuthableProfile = {
        ...createMockUserProfile({
          user: { user_id: 'user-123', email: 'test@test.com' },
          points: 0,
          role: 'user' as const,
        }),
        ...createMockUserWithPasswordHash({
          user_id: 'user-123',
          email: 'test@test.com',
          password_hash: 'hashed_password',
        }),
        refresh_token: 'mock-refresh-token',
      };
      vi.mocked(mockedDb.userRepo.findUserWithProfileByEmail).mockResolvedValue(
        mockAuthableProfile,
      );
      vi.mocked(bcrypt.compare).mockResolvedValue(true as never);

      // Act
      if (localStrategyCallbackWrapper.callback) {
        await localStrategyCallbackWrapper.callback(mockReq, 'test@test.com', 'password', done);
      }

      // Assert
      expect(mockedDb.userRepo.findUserWithProfileByEmail).toHaveBeenCalledWith(
        'test@test.com',
        logger,
      );
      expect(bcrypt.compare).toHaveBeenCalledWith('password', 'hashed_password');
      expect(mockedDb.adminRepo.resetFailedLoginAttempts).toHaveBeenCalledWith(
        mockAuthableProfile.user.user_id,
        '127.0.0.1',
        logger,
      );
      // The strategy now just strips auth fields.
      // SECURITY: password_hash and refresh_token are intentionally discarded.
      const {
        password_hash: _password_hash,
        failed_login_attempts: _failed_login_attempts,
        last_failed_login: _last_failed_login,
        refresh_token: _refresh_token,
        ...expectedUserProfile
      } = mockAuthableProfile;
      expect(done).toHaveBeenCalledWith(null, expectedUserProfile);
    });

    it('should call done(null, false) if user is not found', async () => {
      vi.mocked(mockedDb.userRepo.findUserWithProfileByEmail).mockResolvedValue(undefined);

      if (localStrategyCallbackWrapper.callback) {
        await localStrategyCallbackWrapper.callback(mockReq, 'notfound@test.com', 'password', done);
      }

      expect(done).toHaveBeenCalledWith(null, false, { message: 'Incorrect email or password.' });
    });

    it('should call done(null, false) and increment failed attempts on password mismatch', async () => {
      const mockUser = {
        ...createMockUserProfile({
          user: { user_id: 'user-123', email: 'test@test.com' },
          points: 0,
          role: 'user' as const,
        }),
        ...createMockUserWithPasswordHash({
          user_id: 'user-123',
          email: 'test@test.com',
          failed_login_attempts: 1,
        }),
        refresh_token: 'mock-refresh-token',
      };
      vi.mocked(mockedDb.userRepo.findUserWithProfileByEmail).mockResolvedValue(mockUser);
      vi.mocked(bcrypt.compare).mockResolvedValue(false as never);
      // Mock the service to return the next attempt count
      vi.mocked(mockedDb.adminRepo.incrementFailedLoginAttempts).mockResolvedValue(2);

      if (localStrategyCallbackWrapper.callback) {
        await localStrategyCallbackWrapper.callback(
          mockReq,
          'test@test.com',
          'wrong_password',
          done,
        );
      }

      expect(mockedDb.adminRepo.incrementFailedLoginAttempts).toHaveBeenCalledWith(
        mockUser.user.user_id,
        logger,
      );
      expect(mockedDb.adminRepo.logActivity).toHaveBeenCalledWith(
        expect.objectContaining({
          action: 'login_failed_password',
          details: { source_ip: '127.0.0.1', new_attempt_count: 2 },
        }),
        logger,
      );
      expect(done).toHaveBeenCalledWith(null, false, { message: 'Incorrect email or password.' });
    });

    it('should return a lockout message immediately if the final attempt fails', async () => {
      const mockUser = {
        ...createMockUserProfile({
          user: { user_id: 'user-123', email: 'test@test.com' },
          points: 0,
          role: 'user' as const,
        }),
        ...createMockUserWithPasswordHash({
          user_id: 'user-123',
          email: 'test@test.com',
          failed_login_attempts: 4, // This is the 4th failed attempt
        }),
        refresh_token: 'mock-refresh-token',
      };
      vi.mocked(mockedDb.userRepo.findUserWithProfileByEmail).mockResolvedValue(mockUser);
      vi.mocked(bcrypt.compare).mockResolvedValue(false as never);
      // The service will now return 5, which is >= MAX_FAILED_ATTEMPTS (5)
      vi.mocked(mockedDb.adminRepo.incrementFailedLoginAttempts).mockResolvedValue(5);

      if (localStrategyCallbackWrapper.callback) {
        await localStrategyCallbackWrapper.callback(
          mockReq,
          'test@test.com',
          'wrong_password',
          done,
        );
      }

      expect(mockedDb.adminRepo.incrementFailedLoginAttempts).toHaveBeenCalledWith(
        mockUser.user.user_id,
        logger,
      );
      // It should now return the lockout message, not the generic "incorrect password"
      expect(done).toHaveBeenCalledWith(null, false, {
        message: expect.stringContaining('Account is temporarily locked'),
      });
    });

    it('should call done(null, false) for an OAuth user (no password hash)', async () => {
      const mockUser = {
        ...createMockUserProfile({
          user: { user_id: 'oauth-user', email: 'oauth@test.com' },
          points: 0,
          role: 'user' as const,
        }),
        ...createMockUserWithPasswordHash({
          user_id: 'oauth-user',
          email: 'oauth@test.com',
          password_hash: null,
        }),
        refresh_token: 'mock-refresh-token',
      };
      vi.mocked(mockedDb.userRepo.findUserWithProfileByEmail).mockResolvedValue(mockUser);

      if (localStrategyCallbackWrapper.callback) {
        await localStrategyCallbackWrapper.callback(
          mockReq,
          'oauth@test.com',
          'any_password',
          done,
        );
      }

      expect(done).toHaveBeenCalledWith(null, false, {
        message:
          'This account was created using a social login. Please use Google or GitHub to sign in.',
      });
    });

    it('should call done(null, false) if account is locked', async () => {
      const mockUser = {
        ...createMockUserProfile({
          user: { user_id: 'locked-user', email: 'locked@test.com' },
          points: 0,
          role: 'user' as const,
        }),
        ...createMockUserWithPasswordHash({
          user_id: 'locked-user',
          email: 'locked@test.com',
          failed_login_attempts: 5,
          last_failed_login: new Date().toISOString(),
        }),
        refresh_token: 'mock-refresh-token',
      };
      vi.mocked(mockedDb.userRepo.findUserWithProfileByEmail).mockResolvedValue(mockUser);

      if (localStrategyCallbackWrapper.callback) {
        await localStrategyCallbackWrapper.callback(
          mockReq,
          'locked@test.com',
          'any_password',
          done,
        );
      }

      expect(done).toHaveBeenCalledWith(null, false, {
        message: 'Account is temporarily locked. Please try again in 15 minutes.',
      });
    });

    it('should allow login if lockout period has expired', async () => {
      const mockUser = {
        ...createMockUserProfile({
          user: { user_id: 'expired-lock-user', email: 'expired@test.com' },
          points: 0,
          role: 'user' as const,
        }),
        ...createMockUserWithPasswordHash({
          user_id: 'expired-lock-user',
          email: 'expired@test.com',
          failed_login_attempts: 5,
          last_failed_login: new Date(Date.now() - 20 * 60 * 1000).toISOString(),
        }),
        refresh_token: 'mock-refresh-token',
      };
      vi.mocked(mockedDb.userRepo.findUserWithProfileByEmail).mockResolvedValue(mockUser);
      vi.mocked(bcrypt.compare).mockResolvedValue(true as never); // Correct password

      if (localStrategyCallbackWrapper.callback) {
        await localStrategyCallbackWrapper.callback(
          mockReq,
          'expired@test.com',
          'correct_password',
          done,
        );
      }

      // Should proceed to successful login
      expect(mockedDb.adminRepo.resetFailedLoginAttempts).toHaveBeenCalled();
      expect(done).toHaveBeenCalledWith(null, expect.any(Object));
    });

    it('should call done(err) if the database lookup fails', async () => {
      const dbError = new Error('DB connection failed');
      vi.mocked(mockedDb.userRepo.findUserWithProfileByEmail).mockRejectedValue(dbError);

      if (localStrategyCallbackWrapper.callback) {
        await localStrategyCallbackWrapper.callback(mockReq, 'any@test.com', 'any_password', done);
      }

      expect(done).toHaveBeenCalledWith(dbError);
    });
  });

  describe('JwtStrategy (Isolated Callback Logic)', () => {
    it('should call done(null, userProfile) on successful authentication', async () => {
      // Arrange
      const jwtPayload = { user_id: 'user-123' };
      const mockProfile = {
        role: 'user',
        points: 100,
        user: { user_id: 'user-123', email: 'test@test.com' },
      } as UserProfile;
      vi.mocked(mockedDb.userRepo.findUserProfileById).mockResolvedValue(mockProfile);
      const done = vi.fn();

      // Act: Invoke the captured callback from the wrapper
      // Use a non-null assertion `!` because we know the mock setup populates it.
      if (verifyCallbackWrapper.callback) {
        await verifyCallbackWrapper.callback(jwtPayload, done);
      }

      // Assert
      expect(mockedDb.userRepo.findUserProfileById).toHaveBeenCalledWith('user-123', logger);
      expect(done).toHaveBeenCalledWith(null, mockProfile);
    });

    it('should call done(null, false) and log warning when user profile is not found', async () => {
      // Arrange: findUserProfileById returns undefined (user not in DB)
      const jwtPayload = { user_id: 'non-existent-user' };
      vi.mocked(mockedDb.userRepo.findUserProfileById).mockResolvedValue(undefined as never);
      const done = vi.fn();

      // Act
      if (verifyCallbackWrapper.callback) {
        await verifyCallbackWrapper.callback(jwtPayload, done);
      }

      // Assert: Lines 305-306 - warn logged and done(null, false) called
      expect(logger.warn).toHaveBeenCalledWith(
        'JWT authentication failed: user with ID non-existent-user not found.',
      );
      expect(done).toHaveBeenCalledWith(null, false);
    });

    it('should call done(err, false) when repository throws an error', async () => {
      // Arrange
      const jwtPayload = { user_id: 'non-existent-user' };
      // Per ADR-001, the repository method throws an error when the user is not found.
      // The JWT strategy's catch block will then handle this and call done(err, false).
      const notFoundError = new Error('User not found');
      vi.mocked(mockedDb.userRepo.findUserProfileById).mockRejectedValue(notFoundError);
      const done = vi.fn();

      // Act
      if (verifyCallbackWrapper.callback) {
        await verifyCallbackWrapper.callback(jwtPayload, done);
      }

      // Assert
      // The strategy's catch block passes the error to done().
      expect(done).toHaveBeenCalledWith(notFoundError, false);
    });

    it('should call done(err) if the database lookup fails', async () => {
      // Arrange
      const jwtPayload = { user_id: 'user-123' };
      const dbError = new Error('DB connection failed');
      vi.mocked(mockedDb.userRepo.findUserProfileById).mockRejectedValue(dbError);
      const done = vi.fn();

      // Act
      if (verifyCallbackWrapper.callback) {
        await verifyCallbackWrapper.callback(jwtPayload, done);
      }

      // Assert
      expect(done).toHaveBeenCalledWith(dbError, false);
    });

    it('should call done(err, false) if jwt_payload is null', async () => {
      // Arrange
      const jwtPayload = null;
      const done = vi.fn();

      // Act
      // We know the mock setup populates the callback.
      if (verifyCallbackWrapper.callback) {
        // The strategy would not even call the callback if the token is invalid/missing.
        // However, to test the robustness of our callback, we can invoke it directly with null.
        await verifyCallbackWrapper.callback(jwtPayload as any, done);
      }

      // Assert
      // The code will throw a TypeError because it tries to access 'user_id' of null.
      // The catch block in the strategy will catch this and call done(err, false).
      expect(done).toHaveBeenCalledWith(expect.any(TypeError), false);
      expect(logger.error).toHaveBeenCalledWith(
        { error: expect.any(TypeError) },
        'Error during JWT authentication strategy:',
      );
    });
  });

  describe('isAdmin Middleware', () => {
    const mockNext: NextFunction = vi.fn();
    let mockRes: Partial<Response>;

    beforeEach(() => {
      // Reset response mock for each test
      mockRes = {
        status: vi.fn().mockReturnThis(),
        json: vi.fn(),
      };
    });

    it('should call next() if user has "admin" role', () => {
      // Arrange
      const mockReq = createMockRequest({
        user: createMockUserProfile({
          role: 'admin',
          user: { user_id: 'admin-id', email: 'admin@test.com' },
        }),
      });

      // Act
      isAdmin(mockReq as Request, mockRes as Response, mockNext);

      // Assert
      expect(mockNext).toHaveBeenCalledTimes(1);
      expect(mockRes.status).not.toHaveBeenCalled();
    });

    it('should call next with a ForbiddenError if user does not have "admin" role', () => {
      // Arrange
      const mockReq = createMockRequest({
        user: createMockUserProfile({
          role: 'user',
          user: { user_id: 'user-id', email: 'user@test.com' },
        }),
      });

      // Act
      isAdmin(mockReq as Request, mockRes as Response, mockNext);

      // Assert
      expect(mockNext).toHaveBeenCalledWith(expect.any(ForbiddenError));
      expect(mockRes.status).not.toHaveBeenCalled();
    });

    it('should call next with a ForbiddenError if req.user is missing', () => {
      // Arrange
      const mockReq = createMockRequest(); // No req.user

      // Act
      isAdmin(mockReq, mockRes as Response, mockNext);

      // Assert
      expect(mockNext).toHaveBeenCalledWith(expect.any(ForbiddenError));
      expect(mockRes.status).not.toHaveBeenCalled();
    });

    it('should log a warning when a non-admin user tries to access an admin route', () => {
      // Arrange
      const mockReq = createMockRequest({
        user: createMockUserProfile({
          role: 'user',
          user: { user_id: 'user-id-123', email: 'user@test.com' },
        }),
      });

      // Act
      isAdmin(mockReq as Request, mockRes as Response, mockNext);

      // Assert
      expect(logger.warn).toHaveBeenCalledWith('Admin access denied for user: user-id-123');
    });

    it('should log a warning with "unknown" user when req.user is missing', () => {
      // Arrange
      const mockReq = createMockRequest(); // No req.user

      // Act
      isAdmin(mockReq, mockRes as Response, mockNext);

      // Assert
      expect(logger.warn).toHaveBeenCalledWith('Admin access denied for user: unknown');
    });

    it('should call next with a ForbiddenError for various invalid user object shapes', () => {
      const mockNext = vi.fn();
      const mockRes: Partial<Response> = {
        status: vi.fn().mockReturnThis(),
        json: vi.fn(),
      };

      // Case 1: user is not an object (e.g., a string)
      const req1 = createMockRequest({ user: 'not-an-object' } as any);
      isAdmin(req1, mockRes as Response, mockNext);
      expect(mockNext).toHaveBeenLastCalledWith(expect.any(ForbiddenError));
      expect(mockRes.status).not.toHaveBeenCalled();
      vi.clearAllMocks();

      // Case 2: user is null
      const req2 = createMockRequest({ user: null } as any);
      isAdmin(req2, mockRes as Response, mockNext);
      expect(mockNext).toHaveBeenLastCalledWith(expect.any(ForbiddenError));
      expect(mockRes.status).not.toHaveBeenCalled();
      vi.clearAllMocks();

      // Case 3: user object is missing 'user' property
      const req3 = createMockRequest({ user: { role: 'admin' } } as any);
      isAdmin(req3, mockRes as Response, mockNext);
      expect(mockNext).toHaveBeenLastCalledWith(expect.any(ForbiddenError));
      expect(mockRes.status).not.toHaveBeenCalled();
      vi.clearAllMocks();

      // Case 4: user.user is not an object
      const req4 = createMockRequest({ user: { role: 'admin', user: 'not-an-object' } } as any);
      isAdmin(req4, mockRes as Response, mockNext);
      expect(mockNext).toHaveBeenLastCalledWith(expect.any(ForbiddenError));
      expect(mockRes.status).not.toHaveBeenCalled();
      vi.clearAllMocks();

      // Case 5: user.user is missing 'user_id'
      const req5 = createMockRequest({
        user: { role: 'admin', user: { email: 'test@test.com' } } as any,
      });
      isAdmin(req5, mockRes as Response, mockNext);
      expect(mockNext).toHaveBeenLastCalledWith(expect.any(ForbiddenError));
      expect(mockRes.status).not.toHaveBeenCalled();
      vi.clearAllMocks();

      // Reset the main mockNext for other tests in the suite
      mockNext.mockClear();
    });

    it('should call next with a ForbiddenError if req.user is not a valid UserProfile object', () => {
      // Arrange
      const mockReq = createMockRequest({
        // An object that is not a valid UserProfile (e.g., missing 'role')
        user: {
          user: { user_id: 'invalid-user-id' }, // Missing 'role' property
        } as unknown as UserProfile, // Cast to UserProfile to satisfy req.user type, but it's intentionally malformed
      });

      // Act
      isAdmin(mockReq as Request, mockRes as Response, mockNext);

      // Assert
      expect(mockNext).toHaveBeenCalledWith(expect.any(ForbiddenError));
      expect(mockRes.status).not.toHaveBeenCalled();
    });
  });

  describe('optionalAuth Middleware', () => {
    const mockNext: NextFunction = vi.fn();
    let mockRes: Partial<Response>;

    beforeEach(() => {
      mockRes = { status: vi.fn().mockReturnThis(), json: vi.fn() };
    });

    it('should populate req.user and call next() if authentication succeeds', () => {
      // Arrange
      const mockReq = createMockRequest();
      const mockUser = createMockUserProfile({
        role: 'admin',
        user: { user_id: 'admin-id', email: 'admin@test.com' },
      });
      // Mock passport.authenticate to call its callback with a user
      vi.mocked(passport.authenticate).mockImplementation(
        (_strategy, _options, callback) => () => callback?.(null, mockUser, undefined),
      );

      // Act
      optionalAuth(mockReq, mockRes as Response, mockNext);

      // Assert
      expect(mockReq.user).toEqual(mockUser);
      expect(mockNext).toHaveBeenCalledTimes(1);
    });

    it('should not populate req.user and still call next() if authentication fails', () => {
      // Arrange
      const mockReq = createMockRequest();
      vi.mocked(passport.authenticate).mockImplementation(
        (_strategy, _options, callback) => () => callback?.(null, false, undefined),
      );

      optionalAuth(mockReq, mockRes as Response, mockNext);

      expect(mockReq.user).toBeUndefined();
      expect(mockNext).toHaveBeenCalledTimes(1);
    });

    it('should log info and call next() if authentication provides an info message', () => {
      // Arrange
      const mockReq = createMockRequest();
      const mockInfo = { message: 'Token expired' };
      // Mock passport.authenticate to call its callback with an info object
      vi.mocked(passport.authenticate).mockImplementation(
        (_strategy, _options, callback) => () => callback?.(null, false, mockInfo),
      );

      // Act
      optionalAuth(mockReq, mockRes as Response, mockNext);

      // Assert
      // Pino logger convention: (obj, msg)
      expect(logger.info).toHaveBeenCalledWith({ info: 'Token expired' }, 'Optional auth info:');
      expect(mockNext).toHaveBeenCalledTimes(1);
    });

    it('should log info and call next() if authentication provides an info Error object', () => {
      // Arrange
      const mockReq = createMockRequest();
      const mockInfoError = new Error('Token is malformed');
      // Mock passport.authenticate to call its callback with an info object
      vi.mocked(passport.authenticate).mockImplementation(
        (_strategy, _options, callback) => () => callback?.(null, false, mockInfoError),
      );

      // Act
      optionalAuth(mockReq, mockRes as Response, mockNext);

      // Assert
      // info.message is 'Token is malformed'
      expect(logger.info).toHaveBeenCalledWith(
        { info: 'Token is malformed' },
        'Optional auth info:',
      );
      expect(mockNext).toHaveBeenCalledTimes(1);
    });

    it('should log info.toString() if info object has no message property', () => {
      // Arrange
      const mockReq = createMockRequest();
      const mockInfo = { custom: 'some info' };
      // Mock passport.authenticate to call its callback with a custom info object
      vi.mocked(passport.authenticate).mockImplementation(
        (_strategy, _options, callback) => () => callback?.(null, false, mockInfo as any),
      );

      // Act
      optionalAuth(mockReq, mockRes as Response, mockNext);

      // Assert
      expect(logger.info).toHaveBeenCalledWith(
        { info: mockInfo.toString() },
        'Optional auth info:',
      );
      expect(mockNext).toHaveBeenCalledTimes(1);
    });

    it('should call next() and not populate user if passport returns an error', () => {
      // Arrange
      const mockReq = createMockRequest();
      const authError = new Error('Malformed token');
      // Mock passport.authenticate to call its callback with an error
      vi.mocked(passport.authenticate).mockImplementation(
        (_strategy, _options, callback) => () => callback?.(authError, false, undefined),
      );

      // Act
      optionalAuth(mockReq, mockRes as Response, mockNext);

      // Assert
      // The new implementation logs a warning and proceeds.
      expect(logger.warn).toHaveBeenCalledWith(
        { error: authError },
        'Optional auth encountered an error, proceeding anonymously.',
      );
      expect(mockReq.user).toBeUndefined();
      expect(mockNext).toHaveBeenCalledTimes(1);
    });
  });

  describe('mockAuth Middleware', () => {
    const mockNext: NextFunction = vi.fn(); // This was a duplicate, fixed.
    const mockRes: Partial<Response> = {
      status: vi.fn().mockReturnThis(),
      json: vi.fn(),
    };

    beforeEach(() => {
      // Unstub env variables before each test in this block to ensure a clean state.
      vi.unstubAllEnvs();
    });

    it('should attach a mock admin user to req when NODE_ENV is "test"', () => {
      // Arrange
      vi.stubEnv('NODE_ENV', 'test');
      const mockReq = createMockRequest();

      // Act
      mockAuth(mockReq, mockRes as Response, mockNext);

      // Assert
      expect(mockReq.user).toBeDefined();
      expect((mockReq.user as UserProfile).role).toBe('admin');
      expect(mockNext).toHaveBeenCalledTimes(1);
    });

    it('should do nothing and call next() when NODE_ENV is not "test"', () => {
      // Arrange
      vi.stubEnv('NODE_ENV', 'production');
      const mockReq = createMockRequest();

      // Act
      mockAuth(mockReq, mockRes as Response, mockNext);

      // Assert
      expect(mockReq.user).toBeUndefined();
      expect(mockNext).toHaveBeenCalledTimes(1);
    });
  });
});
