import { type DailyStats, type PageViewSource } from "wasp/entities";
import { HttpError, prisma } from "wasp/server";
import { type GetDailyStats } from "wasp/server/operations";

type DailyStatsWithSources = DailyStats & {
  sources: PageViewSource[];
};

type DailyStatsValues = {
  dailyStats: DailyStatsWithSources;
  weeklyStats: DailyStatsWithSources[];
};

export const getDailyStats: GetDailyStats<
  void,
  DailyStatsValues | undefined
> = async (_args, context) => {
  if (!context.user) {
    throw new HttpError(
      401,
      "Only authenticated users are allowed to perform this operation",
    );
  }

  if (!context.user.isAdmin) {
    throw new HttpError(
      403,
      "Only admins are allowed to perform this operation",
    );
  }

  const statsQuery = {
    orderBy: {
      date: "desc",
    },
    include: {
      sources: true,
    },
  } as const;

  const [dailyStats, weeklyStats] = await prisma.$transaction([
    context.entities.DailyStats.findFirst(statsQuery),
    context.entities.DailyStats.findMany({ ...statsQuery, take: 7 }),
  ]);

  if (!dailyStats) {
    console.log(
      "\x1b[34mNote: No daily stats have been generated by the dailyStatsJob yet. \x1b[0m",
    );
    return undefined;
  }

  return { dailyStats, weeklyStats };
};
