import { createMiddleware } from 'hono/factory';
import { db } from '../db/index';
import { auditLog } from '../db/schema';

/**
 * Audit middleware — automatically logs mutations (POST, PUT, PATCH, DELETE)
 * Wraps the response and captures what changed.
 */
export const auditMiddleware = createMiddleware(async (c, next) => {
  const method = c.req.method;

  // Only audit mutations
  if (!['POST', 'PUT', 'PATCH', 'DELETE'].includes(method)) {
    return next();
  }

  const startTime = Date.now();
  await next();
  const duration = Date.now() - startTime;

  // Only audit successful mutations
  if (c.res.status >= 400) return;

  const auth = c.get('auth');
  const path = new URL(c.req.url).pathname;

  // Extract entity info from the path
  const pathParts = path.split('/').filter(Boolean);
  // Pattern: /v1/{entityType}/{entityId}/...
  const entityType = pathParts[1] || 'unknown';
  const entityId = pathParts[2] || 'unknown';

  // Determine action from method + path
  const actionSuffix = pathParts[3] || (method === 'POST' ? 'created' : method === 'DELETE' ? 'deleted' : 'updated');
  const action = `${entityType}.${actionSuffix}`;

  try {
    await db.insert(auditLog).values({
      actorType: auth?.role === 'agent' ? 'agent' : 'user',
      actorId: auth?.userId,
      actorName: auth?.userId,
      action,
      entityType,
      entityId,
      metadata: {
        method,
        path,
        duration_ms: duration,
        ip: c.req.header('X-Forwarded-For') || c.req.header('X-Real-IP') || 'unknown',
        userAgent: c.req.header('User-Agent'),
      },
    });
  } catch (err) {
    // Audit logging should never break the request
    console.error('[Audit] Failed to log:', err);
  }
});
