import { Password as DefaultPassword } from '@convex-dev/auth/providers/Password';
import { ConvexError } from 'convex/values';

import { UseSendOTP, UseSendOTPPasswordReset } from '..';
import { DataModel } from '../../../_generated/dataModel';

export const Password = DefaultPassword<DataModel>({
  profile(params, ctx) {
    return {
      email: params.email as string,
      name: params.name as string,
    };
  },
  validatePasswordRequirements: (password: string) => {
    if (!validatePassword(password)) {
      throw new ConvexError('Invalid password.');
    }
  },
  reset: UseSendOTPPasswordReset,
  verify: UseSendOTP,
});

export const validatePassword = (password: string): boolean => {
  if (
    password.length < 8 ||
    password.length > 100 ||
    /\s/.test(password) ||
    !/\d/.test(password) ||
    !/[a-z]/.test(password) ||
    !/[A-Z]/.test(password) ||
    !/[\p{P}\p{S}]/u.test(password)
  ) {
    return false;
  }
  return true;
};
