import { Router } from "express";
import { z } from "zod";
import { query } from "../../db/client.js";
import { requireAuth } from "../../middleware/auth.js";
import { requirePermission } from "../../middleware/rbac.js";
import { validateQuery } from "../../middleware/validate.js";

export const auditRouter = Router();
auditRouter.use(requireAuth, requirePermission("admin.audit.view"));

auditRouter.get(
  "/",
  validateQuery(
    z.object({
      page: z.coerce.number().int().min(1).default(1),
      pageSize: z.coerce.number().int().min(5).max(100).default(25),
      action: z.string().max(100).optional(),
      actor: z.coerce.number().int().positive().optional(),
    }),
  ),
  async (req, res, next) => {
    try {
      const { page, pageSize, action, actor } = res.locals.validatedQuery as {
        page: number;
        pageSize: number;
        action?: string;
        actor?: number;
      };
      const conditions: string[] = [];
      const params: unknown[] = [];
      if (action) {
        params.push(`%${action}%`);
        conditions.push(`a.action ILIKE $${params.length}`);
      }
      if (actor) {
        params.push(actor);
        conditions.push(`a.actor_user_id = $${params.length}`);
      }
      const where = conditions.length ? `WHERE ${conditions.join(" AND ")}` : "";
      params.push(pageSize, (page - 1) * pageSize);
      const rows = await query(
        `SELECT a.id, a.occurred_at::text, a.action, a.entity_type, a.entity_id, a.changed_fields,
                a.ip_address::text, a.user_agent, a.context, u.username AS actor_username
           FROM audit_logs a LEFT JOIN users u ON u.id = a.actor_user_id
           ${where}
          ORDER BY a.id DESC
          LIMIT $${params.length - 1} OFFSET $${params.length}`,
        params,
      );
      res.json({ items: rows.rows, page, pageSize });
    } catch (error) {
      next(error);
    }
  },
);
