import { and, desc, eq } from 'drizzle-orm';
import { Router } from 'express';
import { z } from 'zod';

import { db } from '../db/client';
import { auditLogs } from '../db/schema';
import { requireDeviceAuth } from '../middleware/device-auth';

const router = Router();

const querySchema = z.object({
  limit: z.coerce.number().int().min(1).max(100).default(50),
  action: z.string().optional(),
});

router.get('/me', requireDeviceAuth, async (req, res) => {
  const parsed = querySchema.safeParse(req.query);

  if (!parsed.success) {
    res.status(400).json({ message: 'Invalid query params', errors: parsed.error.flatten() });
    return;
  }

  const deviceAuth = req.deviceAuth;

  if (!deviceAuth) {
    res.status(401).json({ message: 'Unauthorized' });
    return;
  }

  const result = await db.query.auditLogs.findMany({
    where: eq(auditLogs.ownerUserId, deviceAuth.userId),
    orderBy: [desc(auditLogs.createdAt)],
    limit: parsed.data.limit,
  });

  const filtered = parsed.data.action ? result.filter((item) => item.action === parsed.data.action) : result;

  res.json({ count: filtered.length, logs: filtered });
});

router.get('/device', requireDeviceAuth, async (req, res) => {
  const parsed = querySchema.safeParse(req.query);

  if (!parsed.success) {
    res.status(400).json({ message: 'Invalid query params', errors: parsed.error.flatten() });
    return;
  }

  const deviceAuth = req.deviceAuth;

  if (!deviceAuth) {
    res.status(401).json({ message: 'Unauthorized' });
    return;
  }

  const result = await db.query.auditLogs.findMany({
    where: and(eq(auditLogs.ownerUserId, deviceAuth.userId), eq(auditLogs.actorDeviceId, deviceAuth.deviceId)),
    orderBy: [desc(auditLogs.createdAt)],
    limit: parsed.data.limit,
  });

  res.json({ count: result.length, logs: result });
});

export default router;
