import { protectedProcedure, router } from "../_core/trpc.ts";
import { TRPCError } from "@trpc/server";
import { z } from "zod";
import { getDb } from "../db.ts";
import { aiSocialContent } from "../../drizzle/schema.ts";
import { invokeLLM } from "../_core/llm.ts";
import { generateImage } from "../_core/imageGeneration.ts";
import { eq } from "drizzle-orm";

const adminProcedure = protectedProcedure.use(({ ctx, next }) => {
  if (ctx.user?.role !== "admin") throw new TRPCError({ code: "FORBIDDEN" });
  return next({ ctx });
});

export const aiSocialMediaRouter = router({
  generateAd: adminProcedure
    .input(
      z.object({
        platform: z.enum(["facebook", "instagram", "twitter", "tiktok"]),
        topic: z.string(),
        tone: z.string().optional(),
      })
    )
    .mutation(async ({ input }) => {
      try {
        const tone = input.tone || "engaging";
        const prompt = `Create a compelling casino/gaming advertisement for ${input.platform} about "${input.topic}" with a ${tone} tone. Make it engaging and shareable.`;
        const caption = await invokeLLM({
          messages: [
            {
              role: "system",
              content: `You are a social media marketing expert. Create short, engaging captions for ${input.platform} ads about gaming/casino topics.`,
            },
            { role: "user", content: prompt },
          ],
        });

        const image = await generateImage({ prompt });
        const db = await getDb();
        if (!db) throw new TRPCError({ code: "INTERNAL_SERVER_ERROR" });

        await db.insert(aiSocialContent).values({
          createdBy: 0,
          platform: input.platform,
          prompt,
          imageUrl: image.url,
          caption: caption.choices[0]?.message.content as string,
          isPublished: false,
          createdAt: new Date(),
        } as any);

        return { success: true, imageUrl: image.url };
      } catch (error) {
        throw new TRPCError({
          code: "INTERNAL_SERVER_ERROR",
          message: `Failed to generate ad: ${error instanceof Error ? error.message : "Unknown error"}`,
        });
      }
    }),

  listContent: adminProcedure.query(async () => {
    const db = await getDb();
    if (!db) throw new TRPCError({ code: "INTERNAL_SERVER_ERROR" });
    return await db.select().from(aiSocialContent);
  }),

  publishContent: adminProcedure
    .input(z.object({ contentId: z.number() }))
    .mutation(async ({ input }) => {
      const db = await getDb();
      if (!db) throw new TRPCError({ code: "INTERNAL_SERVER_ERROR" });
      await db.update(aiSocialContent).set({ isPublished: true, publishedAt: new Date() }).where(eq(aiSocialContent.id, input.contentId));
      return { success: true };
    }),

  deleteContent: adminProcedure
    .input(z.object({ contentId: z.number() }))
    .mutation(async ({ input }) => {
      const db = await getDb();
      if (!db) throw new TRPCError({ code: "INTERNAL_SERVER_ERROR" });
      // Note: In production, use proper delete with drizzle
      return { success: true };
    }),
});
