import { z } from "zod";

// ============================================================================
// Common validation rules
// ============================================================================

export const emailSchema = z.string().email("Invalid email address");

export const passwordSchema = z
  .string()
  .min(8, "Password must be at least 8 characters")
  .regex(/[A-Z]/, "Password must contain at least one uppercase letter")
  .regex(/[a-z]/, "Password must contain at least one lowercase letter")
  .regex(/[0-9]/, "Password must contain at least one number");

export const phoneSchema = z
  .string()
  .regex(/^\+?[1-9]\d{1,14}$/, "Invalid phone number format")
  .optional();

export const dateTimeSchema = z.string().datetime("Invalid datetime format");

// ============================================================================
// User schemas
// ============================================================================

export const userRoleSchema = z.enum([
  "client",
  "trainer",
  "admin",
  "superAdmin",
]);

export const userSchema = z.object({
  email: emailSchema,
  password: passwordSchema,
  firstName: z.string().min(1, "First name is required").max(50),
  lastName: z.string().min(1, "Last name is required").max(50),
  phone: phoneSchema,
  role: userRoleSchema.default("client"),
});

export const userUpdateSchema = userSchema.partial();

export const userLoginSchema = z.object({
  email: emailSchema,
  password: z.string().min(1, "Password is required"),
});

// ============================================================================
// Fitness Goal schemas
// ============================================================================

export const goalTypeSchema = z.enum([
  "weight_target",
  "strength_milestone",
  "endurance_target",
  "flexibility_goal",
  "habit_building",
  "custom",
]);

export const prioritySchema = z.enum(["low", "medium", "high"]);

export const goalStatusSchema = z.enum(["active", "completed", "abandoned"]);

export const fitnessGoalSchema = z.object({
  userId: z.string().min(1, "User ID is required"),
  goalType: goalTypeSchema,
  title: z.string().min(1, "Title is required").max(100),
  description: z.string().max(500).optional(),
  targetValue: z.number().positive("Target value must be positive").optional(),
  currentValue: z
    .number()
    .nonnegative("Current value cannot be negative")
    .optional(),
  unit: z.string().max(20).optional(),
  targetDate: dateTimeSchema.optional(),
  priority: prioritySchema.default("medium"),
  status: goalStatusSchema.default("active"),
  notes: z.string().max(1000).optional(),
});

export const fitnessGoalUpdateSchema = fitnessGoalSchema.partial().omit({
  userId: true,
});

export const fitnessGoalCreateSchema = fitnessGoalSchema.omit({
  userId: true,
});

// ============================================================================
// Fitness Profile schemas
// ============================================================================

export const genderSchema = z.enum([
  "male",
  "female",
  "other",
  "prefer_not_to_say",
]);

export const activityLevelSchema = z.enum([
  "sedentary",
  "lightly_active",
  "moderately_active",
  "very_active",
  "extremely_active",
]);

export const fitnessProfileSchema = z.object({
  userId: z.string().min(1, "User ID is required"),
  height: z
    .number()
    .positive("Height must be positive")
    .max(300, "Invalid height value"),
  weight: z
    .number()
    .positive("Weight must be positive")
    .max(500, "Invalid weight value"),
  age: z
    .number()
    .int("Age must be an integer")
    .positive("Age must be positive")
    .min(13, "Must be at least 13 years old")
    .max(120, "Invalid age value"),
  gender: genderSchema.optional(),
  activityLevel: activityLevelSchema.optional(),
  fitnessGoals: z
    .array(z.string())
    .max(10, "Maximum 10 goals allowed")
    .optional(),
  medicalConditions: z.string().max(1000).optional(),
  allergies: z.string().max(500).optional(),
  injuries: z.string().max(500).optional(),
  preferences: z.string().max(1000).optional(),
});

export const fitnessProfileUpdateSchema = fitnessProfileSchema.partial().omit({
  userId: true,
});

export const fitnessProfileCreateSchema = fitnessProfileSchema.omit({
  userId: true,
});

// ============================================================================
// Recommendation schemas
// ============================================================================

export const recommendationTypeSchema = z.enum([
  "workout",
  "nutrition",
  "lifestyle",
  "recovery",
]);

export const recommendationStatusSchema = z.enum([
  "pending",
  "accepted",
  "rejected",
  "completed",
]);

export const recommendationSchema = z.object({
  userId: z.string().min(1, "User ID is required"),
  type: recommendationTypeSchema,
  title: z.string().min(1, "Title is required").max(200),
  description: z.string().min(1, "Description is required").max(2000),
  reasoning: z.string().max(1000).optional(),
  priority: prioritySchema.default("medium"),
  status: recommendationStatusSchema.default("pending"),
  metadata: z.record(z.unknown()).optional(),
  aiGenerated: z.boolean().default(false),
});

export const recommendationUpdateSchema = recommendationSchema.partial().omit({
  userId: true,
});

// ============================================================================
// Attendance schemas
// ============================================================================

export const attendanceSchema = z.object({
  userId: z.string().min(1, "User ID is required"),
  gymId: z.string().min(1, "Gym ID is required"),
  checkInTime: dateTimeSchema,
  checkOutTime: dateTimeSchema.optional(),
});

export const checkInSchema = z.object({
  userId: z.string().min(1, "User ID is required"),
  gymId: z.string().min(1, "Gym ID is required"),
});

export const checkOutSchema = z.object({
  userId: z.string().min(1, "User ID is required"),
  attendanceId: z.string().min(1, "Attendance ID is required"),
});

// ============================================================================
// Type exports (inferred from schemas)
// ============================================================================

export type User = z.infer<typeof userSchema>;
export type UserUpdate = z.infer<typeof userUpdateSchema>;
export type UserLogin = z.infer<typeof userLoginSchema>;
export type UserRole = z.infer<typeof userRoleSchema>;

export type FitnessGoal = z.infer<typeof fitnessGoalSchema>;
export type FitnessGoalUpdate = z.infer<typeof fitnessGoalUpdateSchema>;
export type FitnessGoalCreate = z.infer<typeof fitnessGoalCreateSchema>;
export type GoalType = z.infer<typeof goalTypeSchema>;
export type GoalStatus = z.infer<typeof goalStatusSchema>;

export type FitnessProfile = z.infer<typeof fitnessProfileSchema>;
export type FitnessProfileUpdate = z.infer<typeof fitnessProfileUpdateSchema>;
export type FitnessProfileCreate = z.infer<typeof fitnessProfileCreateSchema>;
export type Gender = z.infer<typeof genderSchema>;
export type ActivityLevel = z.infer<typeof activityLevelSchema>;

export type Recommendation = z.infer<typeof recommendationSchema>;
export type RecommendationUpdate = z.infer<typeof recommendationUpdateSchema>;
export type RecommendationType = z.infer<typeof recommendationTypeSchema>;
export type RecommendationStatus = z.infer<typeof recommendationStatusSchema>;

export type Attendance = z.infer<typeof attendanceSchema>;
export type CheckIn = z.infer<typeof checkInSchema>;
export type CheckOut = z.infer<typeof checkOutSchema>;

export type Priority = z.infer<typeof prioritySchema>;
