import Isikukood from 'isikukood';
import parsePhoneNumber from 'libphonenumber-js/min';
import { z } from 'zod';

const updateAccountSchema = {
  firstName: z
    .string({
      error: 'First name is required',
    })
    .nonempty(),
  lastName: z
    .string({
      error: 'Last name is required',
    })
    .nonempty({
      error: 'common:formFieldError.stringNonEmpty',
    }),
  personalCode: z.string().refine(
    (val) => {
      try {
        return new Isikukood(val).validate();
      } catch {
        return false;
      }
    },
    {
      message: 'common:formFieldError.invalidPersonalCode',
    },
  ),
  email: z.string().email({
    message: 'Email is required',
  }),
  phone: z
    .string({
      error: 'error:invalidPhone',
    })
    .nonempty()
    .refine(
      (phone) => {
        try {
          const phoneNumber = parsePhoneNumber(phone);
          return (
            !!phoneNumber &&
            phoneNumber.isValid() &&
            phoneNumber.country === 'EE'
          );
        } catch {
          return false;
        }
      },
      {
        message: 'common:formFieldError.invalidPhoneNumber',
      },
    ),
  city: z.string().optional(),
  weight: z
    .number({
      error: (issue) =>
        issue.input === undefined
          ? 'Weight is required'
          : 'Weight must be a number',
    })
    .gt(0, { message: 'Weight must be greater than 0' }),

  height: z
    .number({
      error: (issue) =>
        issue.input === undefined
          ? 'Height is required'
          : 'Height must be a number',
    })
    .gt(0, { message: 'Height must be greater than 0' }),
  userConsent: z.boolean().refine((val) => val === true, {
    message: 'Must be true',
  }),
} as const;
export const UpdateAccountSchemaServer = z.object({
  firstName: updateAccountSchema.firstName,
  lastName: updateAccountSchema.lastName,
  personalCode: updateAccountSchema.personalCode,
  email: updateAccountSchema.email,
  phone: updateAccountSchema.phone,
  city: updateAccountSchema.city,
  weight: updateAccountSchema.weight.nullable(),
  height: updateAccountSchema.height.nullable(),
  userConsent: updateAccountSchema.userConsent,
});
export const UpdateAccountSchemaClient = ({
  isEmailUser,
}: {
  isEmailUser: boolean;
}) =>
  z.object({
    firstName: updateAccountSchema.firstName,
    lastName: updateAccountSchema.lastName,
    personalCode: updateAccountSchema.personalCode,
    email: updateAccountSchema.email,
    phone: updateAccountSchema.phone,
    ...(isEmailUser
      ? {
          city: z.string().optional(),
          weight: z.number().optional(),
          height: z.number().optional(),
        }
      : {
          city: updateAccountSchema.city,
          weight: updateAccountSchema.weight,
          height: updateAccountSchema.height,
        }),
    userConsent: updateAccountSchema.userConsent,
  });
