import { router, publicProcedure } from "../_core/trpc.ts";
import { z } from "zod";
import { registerUser, authenticateUser, resetPassword } from "../services/passwordAuth.ts";
import { sdk } from "../_core/sdk.ts";
import { getSessionCookieOptions } from "../_core/cookies.ts";
import { COOKIE_NAME } from "../../shared/const.ts";

const ONE_YEAR_MS = 365 * 24 * 60 * 60 * 1000;

export const emailAuthRouter = router({
  // Sign up with email and password
  signup: publicProcedure
    .input(
      z.object({
        email: z.string().email(),
        password: z.string().min(8, "Password must be at least 8 characters"),
        name: z.string().min(1, "Name is required"),
      })
    )
    .mutation(async ({ input, ctx }) => {
      try {
        const user = await registerUser(input.email, input.password, input.name);
        
        // Create session token
        const sessionToken = await sdk.createSessionToken(user.openId, {
          name: user.name || "",
          expiresInMs: ONE_YEAR_MS,
        });

        // Set session cookie with maxAge
        const cookieOptions = getSessionCookieOptions(ctx.req);
        ctx.res.cookie(COOKIE_NAME, sessionToken, { ...cookieOptions, maxAge: ONE_YEAR_MS });

        return {
          success: true,
          user: {
            id: user.id,
            email: user.email,
            name: user.name,
            openId: user.openId,
          },
        };
      } catch (error) {
        throw new Error(error instanceof Error ? error.message : "Signup failed");
      }
    }),

  // Login with email and password
  login: publicProcedure
    .input(
      z.object({
        email: z.string().email(),
        password: z.string(),
      })
    )
    .mutation(async ({ input, ctx }) => {
      try {
        const user = await authenticateUser(input.email, input.password);
        
        // Create session token
        const sessionToken = await sdk.createSessionToken(user.openId, {
          name: user.name || "",
          expiresInMs: ONE_YEAR_MS,
        });

        // Set session cookie with maxAge
        const cookieOptions = getSessionCookieOptions(ctx.req);
        ctx.res.cookie(COOKIE_NAME, sessionToken, { ...cookieOptions, maxAge: ONE_YEAR_MS });

        return {
          success: true,
          user: {
            id: user.id,
            email: user.email,
            name: user.name,
            openId: user.openId,
          },
        };
      } catch (error) {
        throw new Error(error instanceof Error ? error.message : "Login failed");
      }
    }),

  // Request password reset
  requestPasswordReset: publicProcedure
    .input(z.object({ email: z.string().email() }))
    .mutation(async ({ input }) => {
      try {
        // In production, send reset link via email
        // For now, just acknowledge the request
        return {
          success: true,
          message: "If an account exists with this email, you will receive a password reset link.",
        };
      } catch (error) {
        throw new Error(error instanceof Error ? error.message : "Password reset request failed");
      }
    }),

  // Reset password with token
  resetPassword: publicProcedure
    .input(
      z.object({
        email: z.string().email(),
        newPassword: z.string().min(8, "Password must be at least 8 characters"),
      })
    )
    .mutation(async ({ input }) => {
      try {
        await resetPassword(input.email, input.newPassword);
        return {
          success: true,
          message: "Password reset successfully. Please log in with your new password.",
        };
      } catch (error) {
        throw new Error(error instanceof Error ? error.message : "Password reset failed");
      }
    }),
});
