import { MongoClientService, MONGO_COLLECTIONS } from '../database/mongo';
import { AuditLog } from './schemas';

export class AuditRepository {
	async insert(log: AuditLog): Promise<void> {
		const db = await MongoClientService.getDb();
		await db.collection(MONGO_COLLECTIONS.AUDIT_LOGS).insertOne(log);
	}

	async findByUserId(userId: string, limit = 100): Promise<AuditLog[]> {
		const db = await MongoClientService.getDb();
		const cursor = db
			.collection(MONGO_COLLECTIONS.AUDIT_LOGS)
			.find({ userId })
			.sort({ createdAt: -1 })
			.limit(limit);
		const results = await cursor.toArray();
		return results as unknown as AuditLog[];
	}

	async findByEventType(eventType: string, limit = 100): Promise<AuditLog[]> {
		const db = await MongoClientService.getDb();
		const cursor = db
			.collection(MONGO_COLLECTIONS.AUDIT_LOGS)
			.find({ eventType })
			.sort({ createdAt: -1 })
			.limit(limit);
		const results = await cursor.toArray();
		return results as unknown as AuditLog[];
	}
}
