import { z } from 'zod';

export const signupSchema = z.object({
  name: z.string().min(2).max(120),
  email: z.string().email().toLowerCase(),
  phone: z.string().min(7).max(20).optional(),
  password: z.string().min(8, 'Password must be at least 8 characters').max(200),
});

export const loginSchema = z.object({
  email: z.string().email().toLowerCase(),
  password: z.string().min(1),
  /**
   * Sent by clients that can complete a two-step sign-in. Older app builds
   * never send it, and for them nothing changes unless the account has 2FA
   * on — in which case they get a readable "update the app" error rather
   * than a response shape they cannot parse.
   */
  supportsTwoFactor: z.boolean().optional(),
  /** Newer clients can ask for an authenticator-app code instead of an email. */
  supportsTotp: z.boolean().optional(),
  /**
   * Sent by clients that can show an Enterprise tenant its own screens. An
   * older app build would treat one as a hostel, so it gets a readable "update
   * the app" error instead. See docs/enterprise/mobile-contract.md.
   */
  supportsEnterprise: z.boolean().optional(),
});

const challengeId = z.string().uuid('Invalid verification reference');
export const otpVerifySchema = z.object({
  challengeId,
  code: z.string().trim().regex(/^\d{6}$/, 'Enter the 6-digit code from the email'),
});
export const otpResendSchema = z.object({ challengeId });
export const profileOtpResendSchema = z.object({ challengeId, purpose: z.enum(['enable', 'disable']) });

export type SignupInput = z.infer<typeof signupSchema>;
export type LoginInput = z.infer<typeof loginSchema>;

export const updateProfileSchema = z
  .object({
    name: z.string().min(2).max(120),
    email: z.string().email().toLowerCase(),
    phone: z.union([z.string().min(7).max(20), z.literal('')]),
  })
  .partial()
  .refine((v) => Object.keys(v).length > 0, 'Nothing to update');

export const changePasswordSchema = z.object({
  currentPassword: z.string().min(1, 'Current password is required'),
  newPassword: z.string().min(8, 'Password must be at least 8 characters').max(200),
});

export type UpdateProfileInput = z.infer<typeof updateProfileSchema>;
export type ChangePasswordInput = z.infer<typeof changePasswordSchema>;

/** An authenticator code (6 digits) or a recovery code ("k7mq-x2pz"). */
const totpOrRecovery = z.string().trim().min(6, 'Enter the 6-digit code, or a recovery code').max(20);
export const totpLoginSchema = z.object({ challengeId, code: totpOrRecovery });
export const loginEmailCodeSchema = z.object({ challengeId });
export const totpCodeSchema = z.object({ code: totpOrRecovery });
export const totpEnableSchema = z.object({ code: z.string().trim().regex(/^\d{6}$/, 'Enter the 6-digit code from the app') });
