import { z } from "zod";
import { createRouter, publicQuery } from "../middleware";
import { getDb } from "../queries/connection";
import { activityLogs } from "@db/schema";
import { desc, sql } from "drizzle-orm";

export const activityRouter = createRouter({
  getRecentSales: publicQuery
    .input(z.object({ limit: z.number().default(10) }).optional())
    .query(async ({ input }) => {
      const db = getDb();
      const limit = input?.limit || 10;
      return db
        .select()
        .from(activityLogs)
        .where(sql`${activityLogs.type} = 'sale'`)
        .orderBy(desc(activityLogs.createdAt))
        .limit(limit);
    }),

  getStats: publicQuery.query(async () => {
    const db = getDb();
    const [saleCount] = await db
      .select({ count: sql<number>`count(*)` })
      .from(activityLogs)
      .where(sql`${activityLogs.type} = 'sale'`);
    const [viewCount] = await db
      .select({ count: sql<number>`count(*)` })
      .from(activityLogs)
      .where(sql`${activityLogs.type} = 'view'`);

    return {
      totalCustomers: (saleCount?.count || 0) * 124 + 10240,
      monthlyActivations: (saleCount?.count || 0) * 31 + 2480,
      weeklyOrders: (saleCount?.count || 0) * 7 + 1240,
      currentVisitors: Math.floor(Math.random() * 40) + 28,
      totalSales: saleCount?.count || 0,
      totalViews: viewCount?.count || 0,
    };
  }),

  getProductStats: publicQuery
    .input(z.object({ productId: z.number() }))
    .query(async ({ input }) => {
      const db = getDb();
      const [productSales] = await db
        .select({ count: sql<number>`count(*)` })
        .from(activityLogs)
        .where(
          sql`${activityLogs.type} = 'sale' AND ${activityLogs.productName} = (SELECT name FROM products WHERE id = ${input.productId})`
        );

      return {
        soldThisWeek: (productSales?.count || 0) * 7 + Math.floor(Math.random() * 100),
        currentViewers: Math.floor(Math.random() * 20) + 5,
        trending: (productSales?.count || 0) > 10,
      };
    }),
});
