import type { NextApiRequest, NextApiResponse } from "next" import { db, schema } from '../../../lib/db/connection' import { eq, and, desc, count } from 'drizzle-orm' export default async function handler(req: NextApiRequest, res: NextApiResponse) { if (req.method !== "GET") return res.status(405).json({ error: "Method not allowed" }) const { page = '1', limit = '50', action, resource_type, user_id } = req.query try { let whereConditions = [] if (action) { whereConditions.push(eq(schema.auditLogs.action, action as string)) } if (resource_type) { whereConditions.push(eq(schema.auditLogs.resourceType, resource_type as string)) } if (user_id) { whereConditions.push(eq(schema.auditLogs.userId, parseInt(user_id as string))) } const offset = (parseInt(page as string) - 1) * parseInt(limit as string) const limitInt = parseInt(limit as string) // Get logs with user info const logs = await db .select({ id: schema.auditLogs.id, userId: schema.auditLogs.userId, userEmail: schema.users.email, action: schema.auditLogs.action, resourceType: schema.auditLogs.resourceType, resourceId: schema.auditLogs.resourceId, details: schema.auditLogs.details, ipAddress: schema.auditLogs.ipAddress, createdAt: schema.auditLogs.createdAt }) .from(schema.auditLogs) .leftJoin(schema.users, eq(schema.auditLogs.userId, schema.users.id)) .where(whereConditions.length > 0 ? and(...whereConditions) : undefined) .orderBy(desc(schema.auditLogs.createdAt)) .limit(limitInt) .offset(offset) // Get total count for pagination const [totalResult] = await db .select({ count: count() }) .from(schema.auditLogs) .where(whereConditions.length > 0 ? and(...whereConditions) : undefined) const total = totalResult.count const totalPages = Math.ceil(total / limitInt) res.json({ logs: logs.map(log => ({ id: log.id, user_id: log.userId, user_email: log.userEmail, action: log.action, resource_type: log.resourceType, resource_id: log.resourceId, details: log.details ? JSON.parse(log.details) : null, ip_address: log.ipAddress, created_at: log.createdAt })), pagination: { page: parseInt(page as string), limit: limitInt, total, totalPages } }) } catch (error) { console.error('Audit logs error:', error) res.status(500).json({ error: "Failed to fetch audit logs" }) } }