import { Hono } from 'hono';
import { eq, and, gte, lte, desc, sql } from 'drizzle-orm';
import { db } from '../db/index';
import { auditLog } from '../db/schema';
import { AuditQuerySchema } from '../types/index';

export const auditRouter = new Hono();

// ─── GET /v1/audit ──────────────────────────────────────
auditRouter.get('/', async (c) => {
  try {
    const query = AuditQuerySchema.parse(c.req.query());
    const { page = 1, limit = 50 } = query;
    const offset = (page - 1) * limit;

    const conditions = [];
    if (query.entityType) conditions.push(eq(auditLog.entityType, query.entityType));
    if (query.entityId) conditions.push(eq(auditLog.entityId, query.entityId));
    if (query.action) conditions.push(eq(auditLog.action, query.action));
    if (query.actorId) conditions.push(eq(auditLog.actorId, query.actorId));
    if (query.since) conditions.push(gte(auditLog.createdAt, new Date(query.since)));
    if (query.until) conditions.push(lte(auditLog.createdAt, new Date(query.until)));

    const where = conditions.length > 0 ? and(...conditions) : undefined;

    const [items, countResult] = await Promise.all([
      db.select().from(auditLog).where(where).orderBy(desc(auditLog.createdAt)).limit(limit).offset(offset),
      db.select({ count: sql<number>`count(*)` }).from(auditLog).where(where),
    ]);

    const total = Number(countResult[0]?.count || 0);

    return c.json({
      success: true,
      data: items,
      meta: { page, limit, total, totalPages: Math.ceil(total / limit) },
    });
  } catch (err: any) {
    if (err.name === 'ZodError') {
      return c.json({ success: false, error: { code: 'VALIDATION_ERROR', message: 'Invalid query', details: err.errors } }, 400);
    }
    return c.json({ success: false, error: { code: 'INTERNAL_ERROR', message: err.message } }, 500);
  }
});
