
import { Request, Response } from 'express';
import { AuditLog } from '../models/AuditLog';
import mongoose from 'mongoose';

export const getLogs = async (req: Request, res: Response) => {
    try {
        const { userId, page = 1, limit = 100 } = req.query;
        let query: any = {};

        if (userId) {
            if (mongoose.Types.ObjectId.isValid(userId as string)) {
                query.userId = new mongoose.Types.ObjectId(userId as string);
            } else {
                query.userId = userId;
            }
        }

        const skip = (Number(page) - 1) * Number(limit);
        const logs = await AuditLog.find(query)
            .sort({ timestamp: -1 })
            .skip(skip)
            .limit(Number(limit));

        const total = await AuditLog.countDocuments(query);

        res.json({
            success: true,
            data: logs,
            pagination: {
                total,
                page: Number(page),
                limit: Number(limit),
                pages: Math.ceil(total / Number(limit)),
                hasMore: Number(page) < Math.ceil(total / Number(limit))
            }
        });
    } catch (error: any) {
        res.status(500).json({ success: false, message: error.message });
    }
};

export const createLog = async (data: {
    userId: string;
    action: string;
    targetCollection: string;
    targetId?: string;
    details: string;
    ipAddress?: string;
    userAgent?: string;
}) => {
    try {
        await AuditLog.create(data);
    } catch (error) {
        console.error('Failed to create audit log:', error);
    }
};
