import { Repository } from 'typeorm';
import { AppDataSource } from '../index';
import { AuditLog } from '../entities/AuditLog.entity';
import { generateUuid } from '../../utils/uuid';

export class AuditLogRepository {
  private repo: Repository<AuditLog>;

  constructor() {
    this.repo = AppDataSource.getRepository(AuditLog);
  }

  log(params: {
    userId?: string | null;
    action: string;
    entityType: string;
    entityId?: string | null;
    metadata?: Record<string, unknown>;
    ipAddress?: string | null;
  }): Promise<AuditLog> {
    return this.repo.save(
      this.repo.create({
        id: generateUuid(),
        userId: params.userId ?? null,
        action: params.action,
        entityType: params.entityType,
        entityId: params.entityId ?? null,
        metadata: params.metadata ?? null,
        ipAddress: params.ipAddress ?? null,
      }),
    );
  }
}
