import { router, publicProcedure, protectedProcedure } from "../_core/trpc.ts";
import { z } from "zod";
import { MagicLinkAuthService } from "../services/magicLinkAuth.ts";

export const authMagicLinkRouter = router({
  /**
   * Send magic link to email
   */
  send: publicProcedure
    .input(
      z.object({
        email: z.string().email(),
        origin: z.string().optional(),
      })
    )
    .mutation(async ({ input }) => {
      try {
        // Generate magic link token
        const token = MagicLinkAuthService.generateToken(input.email);

        // Send email with magic link
        const result = await MagicLinkAuthService.sendMagicLink(
          input.email,
          token,
          input.origin || "https://playcoinkrazy.com"
        );

        return {
          success: true,
          message: "Magic link sent to your email",
          expiresAt: result.expiresAt,
        };
      } catch (error) {
        console.error("[Magic Link] Error sending link:", error);
        throw new Error("Failed to send magic link");
      }
    }),

  /**
   * Verify magic link token
   */
  verify: publicProcedure
    .input(
      z.object({
        token: z.string(),
      })
    )
    .mutation(async ({ input }) => {
      try {
        const user = await MagicLinkAuthService.authenticateWithMagicLink(input.token);

        return {
          success: true,
          user: {
            id: user.id,
            email: user.email,
            name: user.name,
          },
          message: "Magic link verified successfully",
        };
      } catch (error) {
        console.error("[Magic Link] Error verifying token:", error);
        throw new Error("Invalid or expired magic link");
      }
    }),

  /**
   * Check magic link token status
   */
  checkToken: publicProcedure
    .input(
      z.object({
        token: z.string(),
      })
    )
    .query(({ input }) => {
      try {
        const info = MagicLinkAuthService.getTokenInfo(input.token);

        if (!info) {
          return {
            valid: false,
            message: "Token not found",
          };
        }

        return {
          valid: !info.isExpired,
          email: info.email,
          expiresAt: info.expiresAt,
          isExpired: info.isExpired,
        };
      } catch (error) {
        console.error("[Magic Link] Error checking token:", error);
        return {
          valid: false,
          message: "Error checking token",
        };
      }
    }),

  /**
   * Resend magic link
   */
  resend: publicProcedure
    .input(
      z.object({
        email: z.string().email(),
        origin: z.string().optional(),
      })
    )
    .mutation(async ({ input }) => {
      try {
        // Generate new magic link token
        const token = MagicLinkAuthService.generateToken(input.email);

        // Send email
        const result = await MagicLinkAuthService.sendMagicLink(
          input.email,
          token,
          input.origin || "https://playcoinkrazy.com"
        );

        return {
          success: true,
          message: "Magic link resent to your email",
          expiresAt: result.expiresAt,
        };
      } catch (error) {
        console.error("[Magic Link] Error resending link:", error);
        throw new Error("Failed to resend magic link");
      }
    }),

  /**
   * Clean up expired tokens (admin only)
   */
  cleanupExpired: protectedProcedure.mutation(async ({ ctx }) => {
    try {
      // Check if user is admin
      if (ctx.user.role !== "admin") {
        throw new Error("Unauthorized");
      }

      const cleaned = MagicLinkAuthService.cleanupExpiredTokens();

      return {
        success: true,
        cleaned,
        message: `Cleaned up ${cleaned} expired tokens`,
      };
    } catch (error) {
      console.error("[Magic Link] Error cleaning up tokens:", error);
      throw new Error("Failed to cleanup expired tokens");
    }
  }),
});
