import Joi from 'joi';

export interface SignupBody {
  email: string;
  password: string;
}

export interface LoginBody {
  email: string;
  password: string;
}

// 72 chars is bcrypt/Firebase's practical input limit for a password.
const passwordRule = Joi.string()
  .min(8)
  .max(72)
  .required();
  // .pattern(/[a-z]/, 'a lowercase letter')
  // .pattern(/[A-Z]/, 'an uppercase letter')
  // .pattern(/[0-9]/, 'a number')
  
  // Only email + password are ever asked of the end user. Everything else a
  // User row needs (name, avatarUrl, emailVerified, role, ...) is defaulted
  // server-side in auth.controller.ts / auth.model.ts, not collected here.
  export const signupSchema = Joi.object<SignupBody>({
    email: Joi.string().trim().lowercase().email().max(254).required(),
  password: passwordRule,
}).required();

// My profile: people edit their own name and contact details (email is their sign-in, so it stays).
export interface UpdateProfileBody {
  name: string;
  phone?: string | null;
  jobTitle?: string | null;
}

export const updateProfileSchema = Joi.object<UpdateProfileBody>({
  name: Joi.string().trim().min(2).max(120).required(),
  phone: Joi.string().trim().max(30).pattern(/^[+\d][\d\s-]*$/).allow('', null)
    .messages({ 'string.pattern.base': 'Use digits, spaces, dashes and an optional leading +' }),
  jobTitle: Joi.string().trim().max(80).allow('', null),
}).required();

export interface ChangePasswordBody {
  currentPassword: string;
  newPassword: string;
}

// Same rule as accepting an invite: at least 8 characters with a number.
export const changePasswordSchema = Joi.object<ChangePasswordBody>({
  currentPassword: Joi.string().required(),
  newPassword: Joi.string().min(8).max(72).pattern(/\d/).invalid(Joi.ref('currentPassword')).required()
    .messages({
      'string.pattern.base': 'Include at least one number',
      'any.invalid': 'Choose a password different from your current one',
    }),
}).required();

export const loginSchema = Joi.object<LoginBody>({
  email: Joi.string().trim().lowercase().email().max(254).required(),
  password: Joi.string().required(),
}).required();

export interface RefreshBody {
  refreshToken: string;
}

export const refreshSchema = Joi.object<RefreshBody>({
  refreshToken: Joi.string().required(),
}).required();
