import { router, protectedProcedure, adminProcedure } from "../_core/trpc.ts";
import { z } from "zod";
import {
  getAllThemes,
  getCurrentTheme,
  changeTheme,
  getSiteThemeConfig,
  getThemeHistory,
  isValidThemeId,
  type ThemeType,
} from "../services/themeService.ts";

export const adminThemeRouter = router({
  /**
   * Get all available themes
   */
  getAllThemes: protectedProcedure.query(() => {
    return getAllThemes();
  }),

  /**
   * Get current theme
   */
  getCurrentTheme: protectedProcedure.query(() => {
    return getCurrentTheme();
  }),

  /**
   * Get site theme configuration
   */
  getSiteThemeConfig: protectedProcedure.query(() => {
    return getSiteThemeConfig();
  }),

  /**
   * Change sitewide theme (admin only)
   */
  changeTheme: adminProcedure
    .input(
      z.object({
        themeId: z.enum(["blue", "neon-green", "gold"]),
      })
    )
    .mutation(async ({ input, ctx }) => {
      if (!isValidThemeId(input.themeId)) {
        throw new Error("Invalid theme ID");
      }

      const success = changeTheme(input.themeId, ctx.user.id);

      if (!success) {
        throw new Error("Failed to change theme");
      }

      return {
        success: true,
        theme: getCurrentTheme(),
        message: `Theme changed to ${input.themeId} by ${ctx.user.name}`,
      };
    }),

  /**
   * Get theme change history
   */
  getThemeHistory: adminProcedure.query(() => {
    return getThemeHistory();
  }),

  /**
   * Get theme statistics
   */
  getThemeStats: adminProcedure.query(() => {
    const history = getThemeHistory();
    const currentTheme = getCurrentTheme();

    const themeUsage: Record<string, number> = {};
    history.forEach((entry) => {
      themeUsage[entry.theme] = (themeUsage[entry.theme] || 0) + 1;
    });

    return {
      currentTheme: currentTheme.id,
      totalThemeChanges: history.length,
      themeUsage,
      lastChange: history[history.length - 1] || null,
    };
  }),
});
