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 AuditLogsService {
  constructor(
    @InjectModel(AuditLog.name)
    private readonly auditModel: Model<AuditLogDocument>,
  ) {}

  async append(data: {
    actorUserId?: string;
    actorEmail?: string;
    action: string;
    targetType?: string;
    targetId?: string;
    metadata?: Record<string, unknown>;
    ipAddress?: string;
    userAgent?: string;
  }) {
    return this.auditModel.create(data);
  }

  async list(params: { cursor?: string; limit?: number }) {
    const limit = params.limit ?? 50;
    const filter: Record<string, unknown> = {};
    if (params.cursor && Types.ObjectId.isValid(params.cursor)) {
      filter._id = { $lt: new Types.ObjectId(params.cursor) };
    }
    const rows = await this.auditModel
      .find(filter)
      .sort({ createdAt: -1 })
      .limit(limit + 1)
      .lean()
      .exec();
    const hasMore = rows.length > limit;
    const items = hasMore ? rows.slice(0, limit) : rows;
    return {
      items: items.map((r) => ({ ...r, id: r._id.toString() })),
      nextCursor: hasMore ? items[items.length - 1]._id.toString() : null,
    };
  }
}
