import { Module } from '@nestjs/common';

import { LoggingModule } from '../../domain/logging/LoggingModule';

import type { StoredUser } from '@core/identity/domain/repositories/UserRepository';
import type { PasswordHashingService } from '@core/identity/domain/services/PasswordHashingService';
import type { Logger } from '@core/shared/domain/Logger';

import { InMemoryAuthRepository } from '@adapters/identity/persistence/inmemory/InMemoryAuthRepository';
import { InMemoryCompanyRepository } from '@adapters/identity/persistence/inmemory/InMemoryCompanyRepository';
import { InMemoryMagicLinkRepository } from '@adapters/identity/persistence/inmemory/InMemoryMagicLinkRepository';
import { InMemoryUserRepository } from '@adapters/identity/persistence/inmemory/InMemoryUserRepository';
import { InMemoryPasswordHashingService } from '@adapters/identity/services/InMemoryPasswordHashingService';

import { AUTH_REPOSITORY_TOKEN, COMPANY_REPOSITORY_TOKEN, MAGIC_LINK_REPOSITORY_TOKEN, PASSWORD_HASHING_SERVICE_TOKEN, USER_REPOSITORY_TOKEN } from '../identity/IdentityPersistenceTokens';

@Module({
  imports: [LoggingModule],
  providers: [
    {
      provide: USER_REPOSITORY_TOKEN,
      useFactory: (logger: Logger) => {
        const initialUsers: StoredUser[] = [
          {
            // Match seeded racing driver id so dashboard works in inmemory mode.
            id: 'driver-1',
            email: 'admin@gridpilot.local',
            passwordHash: 'demo_salt_321nimda', // InMemoryPasswordHashingService: "admin123" reversed.
            displayName: 'Alex Martinez',
            createdAt: new Date(),
          },
        ];
        return new InMemoryUserRepository(logger, initialUsers);
      },
      inject: ['Logger'],
    },
    {
      provide: AUTH_REPOSITORY_TOKEN,
      useFactory: (userRepository: InMemoryUserRepository, passwordHashingService: PasswordHashingService, logger: Logger) =>
        new InMemoryAuthRepository(userRepository, passwordHashingService, logger),
      inject: [USER_REPOSITORY_TOKEN, PASSWORD_HASHING_SERVICE_TOKEN, 'Logger'],
    },
    {
      provide: PASSWORD_HASHING_SERVICE_TOKEN,
      useClass: InMemoryPasswordHashingService,
    },
    {
      provide: MAGIC_LINK_REPOSITORY_TOKEN,
      useFactory: (logger: Logger) => new InMemoryMagicLinkRepository(logger),
      inject: ['Logger'],
    },
    {
      provide: COMPANY_REPOSITORY_TOKEN,
      useClass: InMemoryCompanyRepository,
    },
  ],
  exports: [USER_REPOSITORY_TOKEN, AUTH_REPOSITORY_TOKEN, PASSWORD_HASHING_SERVICE_TOKEN, MAGIC_LINK_REPOSITORY_TOKEN, COMPANY_REPOSITORY_TOKEN],
})
export class InMemoryIdentityPersistenceModule {}