import { Module, Logger } from '@nestjs/common';
import { PlatformModule } from '../platform/platform.module';
import { IdentityModule } from '../identity/identity.module';
import { MediaController } from './media.controller';
import { MediaService } from './media.service';
import { LocalDiskStorage } from './local-disk.storage';
import { S3Storage, s3ConfigFromEnv } from './s3.storage';
import { STORAGE_PORT, type StoragePort } from './storage.port';

/** S3/MinIO when its env is set (IIOS_S3_BUCKET + keys), else local disk. Env-driven swap. */
function makeStorage(): StoragePort {
  const cfg = s3ConfigFromEnv();
  if (cfg) {
    new Logger('MediaStorage').log(`using S3 storage (bucket "${cfg.bucket}"${cfg.endpoint ? ` @ ${cfg.endpoint}` : ''})`);
    return new S3Storage(cfg);
  }
  return new LocalDiskStorage();
}

@Module({
  imports: [PlatformModule, IdentityModule],
  controllers: [MediaController],
  providers: [MediaService, { provide: STORAGE_PORT, useFactory: makeStorage }],
  // Exported so the capability layer can resolve email attachment bytes at send time.
  exports: [STORAGE_PORT],
})
export class MediaModule {}
