import { Injectable } from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose';
import { Model, Types } from 'mongoose';
import { AuditLog, AuditLogDocument } from './schemas/audit-log.schema';

@Injectable()
export class AuditRepository {
  constructor(@InjectModel(AuditLog.name) private readonly auditModel: Model<AuditLogDocument>) {}

  async create(payload: {
    actorType: 'user' | 'superadmin' | 'system';
    actorUserId?: string;
    actorIdentifier?: string;
    action: string;
    targetType: string;
    targetId?: string;
    metadata?: Record<string, unknown>;
  }): Promise<void> {
    await this.auditModel.create({
      actorType: payload.actorType,
      ...(payload.actorUserId ? { actorUserId: new Types.ObjectId(payload.actorUserId) } : {}),
      actorIdentifier: payload.actorIdentifier,
      action: payload.action,
      targetType: payload.targetType,
      targetId: payload.targetId,
      metadata: payload.metadata ?? {},
    });
  }

  async findMany(
    filter: Record<string, unknown>,
    skip: number,
    limit: number,
    sort: Record<string, 1 | -1> = { createdAt: -1 },
  ): Promise<AuditLogDocument[]> {
    return this.auditModel.find(filter).sort(sort).skip(skip).limit(limit).exec();
  }

  async count(filter: Record<string, unknown>): Promise<number> {
    return this.auditModel.countDocuments(filter).exec();
  }
}
