import type { Filter } from "mongodb";
import { Message, User } from "revolt-api";
import {
  Card,
  CardContent,
  CardDescription,
  CardHeader,
  CardTitle,
} from "../ui/card";
import { fetchMessages, fetchUsersById } from "@/lib/db";
import { CompactMessage } from "../cards/CompactMessage";

export async function RecentMessages({
  query,
  users,
}: {
  query: Filter<Message>;
  users?: boolean | User[];
}) {
  const recentMessages = await fetchMessages(query);

  const userList = (
    users === true
      ? await fetchUsersById([...new Set(recentMessages.map((x) => x.author))])
      : Array.isArray(users)
      ? users
      : []
  ).reduce((prev, next) => {
    prev[next._id] = next;
    return prev;
  }, {} as Record<string, any>);

  return (
    <Card>
      <CardHeader>
        <CardTitle>Recent Messages</CardTitle>
        <CardDescription>Overview of recent messages</CardDescription>
      </CardHeader>
      <CardContent>
        {/* enter reason for fetching */}
        {recentMessages.map((message) => (
          <CompactMessage
            key={message._id}
            message={message}
            hideUser={Object.keys(userList).length === 0}
            users={userList}
          />
        ))}
      </CardContent>
    </Card>
  );
}
