import { Password } from "@convex-dev/auth/providers/Password";
import { convexAuth } from "@convex-dev/auth/server";

/**
 * Convex Auth 配置
 *
 * 配置密码认证方式，支持用户通过邮箱和密码注册/登录。
 */
export const { auth, signIn, signOut, store, isAuthenticated } = convexAuth({
  providers: [
    Password({
      /**
       * 密码要求验证
       */
      validatePasswordRequirements: (password: string) => {
        if (password.length < 8) {
          throw new Error("密码至少需要 8 个字符");
        }
      },

      /**
       * 用户资料配置
       */
      profile(params, _ctx) {
        const email = typeof params.email === "string" ? params.email : String(params.email ?? "");
        const name = typeof params.name === "string" ? params.name : "";
        // 说明：Convex 的 Value 类型不允许 undefined；这里统一给 name 一个字符串占位。
        return { email, name: name.trim() ? name : "" };
      },
    }),
  ],
});
