import { Inject, Injectable, Logger } from '@nestjs/common';
import {
  AUDIT_LOG_REPOSITORY,
  IAuditLogRepository,
} from '../../domain/repositories/audit-log.repository.interface';
import { IAuditLoggerService, AuditLogParams } from '../../domain/ports/audit-logger.interface';

@Injectable()
export class AuditLoggerService implements IAuditLoggerService {
  private readonly logger = new Logger('AuditLoggerService');

  constructor(
    @Inject(AUDIT_LOG_REPOSITORY)
    private readonly auditLogRepo: IAuditLogRepository,
  ) {}

  async log(params: AuditLogParams): Promise<void> {
    const entry = this.auditLogRepo.create({
      adminId: params.adminId,
      adminName: params.adminName,
      action: params.action,
      resource: params.resource,
      resourceId: params.resourceId,
      ipAddress: params.ipAddress || null,
      result: params.result || 'success',
      details: params.details || null,
    });
    await this.auditLogRepo.save(entry);
    this.logger.debug(
      `Audit: action=${params.action} resource=${params.resource} resourceId=${params.resourceId} admin=${params.adminId}`,
    );
  }
}
