import { e as communicationLogs, d as db } from '../../admin/create-upload-progress-table/POST-C-OoiMoW.js';
import { or, and, eq, desc } from 'drizzle-orm';

async function handler(req, res) {
  try {
    const { deviceId, serverId, messageType, limit = "50", offset = "0" } = req.query;
    const limitNum = Math.min(parseInt(limit) || 50, 200);
    const offsetNum = parseInt(offset) || 0;
    const conditions = [];
    if (deviceId) {
      conditions.push(
        or(
          and(eq(communicationLogs.fromType, "device"), eq(communicationLogs.fromId, deviceId)),
          and(eq(communicationLogs.toType, "device"), eq(communicationLogs.toId, deviceId))
        )
      );
    }
    if (serverId) {
      conditions.push(
        or(
          and(eq(communicationLogs.fromType, "server"), eq(communicationLogs.fromId, serverId)),
          and(eq(communicationLogs.toType, "server"), eq(communicationLogs.toId, serverId))
        )
      );
    }
    if (messageType) {
      conditions.push(eq(communicationLogs.messageType, messageType));
    }
    let query = db.select().from(communicationLogs);
    if (conditions.length > 0) {
      query = query.where(and(...conditions));
    }
    const messages = await query.orderBy(desc(communicationLogs.createdAt)).limit(limitNum).offset(offsetNum);
    const totalMessages = messages.length;
    res.json({
      success: true,
      messages,
      total: totalMessages,
      limit: limitNum,
      offset: offsetNum
    });
  } catch (error) {
    console.error("Messages fetch error:", error);
    res.status(500).json({
      success: false,
      error: "Failed to fetch messages",
      message: String(error)
    });
  }
}

export { handler as h };
