import { z } from 'zod'

// Contact form schema
export const contactFormSchema = z.object({
  name: z
    .string()
    .min(2, 'Name must be at least 2 characters')
    .max(100, 'Name must be less than 100 characters')
    .regex(/^[a-zA-Z\s'-]+$/, 'Name can only contain letters, spaces, hyphens, and apostrophes'),
  
  email: z
    .string()
    .min(1, 'Email is required')
    .email('Please enter a valid email address')
    .max(255, 'Email must be less than 255 characters'),
  
  subject: z
    .string()
    .min(3, 'Subject must be at least 3 characters')
    .max(200, 'Subject must be less than 200 characters'),
  
  projectType: z
    .string()
    .optional(),
  
  message: z
    .string()
    .min(10, 'Message must be at least 10 characters')
    .max(2000, 'Message must be less than 2000 characters'),
})

export type ContactFormData = z.infer<typeof contactFormSchema>

// Newsletter subscription schema
export const newsletterSchema = z.object({
  email: z
    .string()
    .min(1, 'Email is required')
    .email('Please enter a valid email address')
    .max(255, 'Email must be less than 255 characters')
    .refine(
      (email) => {
        // Check for common typos in email domains
        const commonDomains = ['gmail.com', 'outlook.com', 'yahoo.com', 'hotmail.com', 'icloud.com']
        const domain = email.split('@')[1]?.toLowerCase()
        return !domain || !domain.includes('..') && domain.split('.').every(part => part.length > 0)
      },
      { message: 'Please check your email format' }
    )
    .transform((email) => email.toLowerCase().trim()),
  
  name: z
    .string()
    .min(2, 'Name must be at least 2 characters')
    .max(100, 'Name must be less than 100 characters')
    .regex(/^[a-zA-Zа-яА-ЯёЁ\s'-]+$/, 'Name can only contain letters, spaces, hyphens, and apostrophes')
    .transform((name) => name.trim())
    .optional()
    .or(z.literal('')),
})

export type NewsletterData = z.infer<typeof newsletterSchema>

// Project filter schema
export const projectFilterSchema = z.object({
  category: z.enum(['All', 'Full Stack', 'AI/ML', 'Real-time', 'Mobile', 'Blockchain', 'Data Science']).optional(),
  search: z.string().optional(),
  tags: z.array(z.string()).optional(),
  sortBy: z.enum(['date', 'popularity', 'name']).optional(),
  sortOrder: z.enum(['asc', 'desc']).optional(),
})

export type ProjectFilterData = z.infer<typeof projectFilterSchema>

// Blog comment schema
export const commentSchema = z.object({
  name: z
    .string()
    .min(2, 'Name must be at least 2 characters')
    .max(100, 'Name must be less than 100 characters'),
  
  email: z
    .string()
    .email('Please enter a valid email address')
    .optional(),
  
  comment: z
    .string()
    .min(5, 'Comment must be at least 5 characters')
    .max(1000, 'Comment must be less than 1000 characters'),
  
  postId: z.string(),
})

export type CommentData = z.infer<typeof commentSchema>

// File upload schema
export const fileUploadSchema = z.object({
  file: z
    .any()
    .refine((file) => file?.size <= 5000000, 'File size must be less than 5MB')
    .refine(
      (file) =>
        ['application/pdf', 'image/jpeg', 'image/png', 'image/gif', 'application/msword', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'].includes(
          file?.type
        ),
      'Invalid file type. Allowed: PDF, JPEG, PNG, GIF, DOC, DOCX'
    ),
  
  description: z
    .string()
    .max(500, 'Description must be less than 500 characters')
    .optional(),
})

export type FileUploadData = z.infer<typeof fileUploadSchema>

// Environment variables schema
export const envSchema = z.object({
  // Site
  NEXT_PUBLIC_SITE_URL: z.string().url().optional(),
  NEXT_PUBLIC_SITE_NAME: z.string().optional(),
  
  // Email
  RESEND_API_KEY: z.string().optional(),
  SMTP_HOST: z.string().optional(),
  SMTP_PORT: z.string().optional(),
  SMTP_USER: z.string().optional(),
  SMTP_PASSWORD: z.string().optional(),
  EMAIL_FROM: z.string().email().optional(),
  EMAIL_TO: z.string().email().optional(),
  
  // Newsletter
  MAILCHIMP_API_KEY: z.string().optional(),
  MAILCHIMP_AUDIENCE_ID: z.string().optional(),
  CONVERTKIT_API_KEY: z.string().optional(),
  CONVERTKIT_FORM_ID: z.string().optional(),
  
  // Analytics
  NEXT_PUBLIC_GA_MEASUREMENT_ID: z.string().optional(),
  NEXT_PUBLIC_GOOGLE_VERIFICATION: z.string().optional(),
  NEXT_PUBLIC_YANDEX_VERIFICATION: z.string().optional(),
  
  // reCAPTCHA
  NEXT_PUBLIC_RECAPTCHA_SITE_KEY: z.string().optional(),
  RECAPTCHA_SECRET_KEY: z.string().optional(),
  
  // Database (if needed)
  DATABASE_URL: z.string().optional(),
  
  // Redis (for rate limiting)
  REDIS_URL: z.string().optional(),
})

export type EnvData = z.infer<typeof envSchema>

// Helper function to validate environment variables
export function validateEnv() {
  try {
    return envSchema.parse(process.env)
  } catch (error) {
    console.error('❌ Invalid environment variables:', error)
    throw new Error('Invalid environment variables')
  }
}

