import { adminProcedure, createTRPCRouter } from "~/server/api/trpc";
import { db } from "~/server/db";
import { sql } from "kysely";

export const statsRouter = createTRPCRouter({
  adminDashStats: adminProcedure.query(async () => {
    const userTimeserie = (
      await db
        .selectFrom("users")
        .select((eb) => [
          sql<Date>`date_trunc('day', created_at)`.as("date"),
          eb.fn.count<number>("id").as("value"),
        ])
        .groupBy("date")
        .orderBy("date")
        .execute()
    ).map((item) => ({
      date: item.date,
      value: parseInt(String(item.value)),
    }));

    const orderTimeserie = (
      await db
        .selectFrom("ordini")
        .select((eb) => [
          sql<Date>`date_trunc('day', created_at)`.as("date"),
          eb.fn.count<number>("ordine_id").as("value"),
        ])
        .groupBy("date")
        .orderBy("date")
        .execute()
    ).map((item) => ({
      date: item.date,
      value: parseInt(String(item.value)),
    }));

    //todo finire
    const contattiTimeserie = (
      await db
        .selectFrom("servizio_annunci")
        .select((eb) => [
          sql<Date>`date_trunc('day', created_at)`.as("date"),
          eb.fn
            .count<number>(eb.fn("concat", ["servizio_id", "annunci_id"]))
            .as("value"),
        ])
        .where("open_contatti_at", "is not", null)
        .groupBy("date")
        .orderBy("date")
        .execute()
    ).map((item) => ({
      date: item.date,
      value: parseInt(String(item.value)),
    }));

    return {
      userTimeserie,
      orderTimeserie,
      contattiTimeserie,
    };
  }),
});
