import { db } from '../config/database.js';
import { auditLogs, users } from '../db/schema.js';
import { desc, eq } from 'drizzle-orm';

export const getRecentAuditLogs = async (req, res, next) => {
  try {
    const { limit = 20, userId } = req.query;

    let query = db
      .select({
        id: auditLogs.id,
        userId: auditLogs.userId,
        action: auditLogs.action,
        resource: auditLogs.resource,
        resourceId: auditLogs.resourceId,
        oldValue: auditLogs.oldValue,
        newValue: auditLogs.newValue,
        success: auditLogs.success,
        createdAt: auditLogs.createdAt,
        // User info
        userFirstName: users.firstName,
        userLastName: users.lastName,
        username: users.username,
      })
      .from(auditLogs)
      .leftJoin(users, eq(auditLogs.userId, users.id))
      .orderBy(desc(auditLogs.createdAt))
      .limit(parseInt(limit));

    if (userId) {
      query = query.where(eq(auditLogs.userId, userId));
    }

    const logs = await query;

    res.json({
      success: true,
      data: logs,
    });
  } catch (error) {
    next(error);
  }
};
