import { z } from 'zod';

// Common validation schemas
export const uuidSchema = z.string().uuid();
export const emailSchema = z.string().email();
export const positiveIntSchema = z.number().int().positive();
export const nonNegativeIntSchema = z.number().int().min(0);

// User authentication schemas
export const signInSchema = z.object({
  email: emailSchema,
  password: z.string().min(8).max(128)
});

export const signUpSchema = z.object({
  email: emailSchema,
  password: z.string().min(8).max(128),
  name: z.string().min(1).max(100),
  organizationName: z.string().min(1).max(100).optional()
});

// Event management schemas
export const eventSchema = z.object({
  title: z.string().min(1).max(200),
  description: z.string().max(5000).optional(),
  venue: z.string().min(1).max(200),
  startTime: z.string().datetime(),
  endTime: z.string().datetime().optional(),
  organizationId: uuidSchema
});

// Ticket schemas
export const ticketTypeSchema = z.object({
  name: z.string().min(1).max(100),
  price: nonNegativeIntSchema,
  quantity: positiveIntSchema,
  eventId: uuidSchema
});

export const purchaseAttemptSchema = z.object({
  eventId: uuidSchema,
  purchaserEmail: emailSchema,
  purchaserName: z.string().min(1).max(100),
  items: z.array(z.object({
    ticketTypeId: uuidSchema,
    quantity: positiveIntSchema
  })).min(1),
  totalAmount: positiveIntSchema
});

export const completePurchaseSchema = z.object({
  purchaseAttemptId: uuidSchema,
  stripePaymentIntentId: z.string().min(1)
});

// Refund schemas
export const refundSchema = z.object({
  ticketId: uuidSchema,
  amount: positiveIntSchema,
  reason: z.string().min(1).max(500)
});

// Admin schemas
export const adminActionSchema = z.object({
  action: z.enum(['create', 'update', 'delete', 'view']),
  resourceType: z.string().min(1).max(50),
  resourceId: uuidSchema.optional(),
  details: z.record(z.any()).optional()
});

// Inventory schemas
export const inventoryReserveSchema = z.object({
  eventId: uuidSchema,
  items: z.array(z.object({
    ticketTypeId: uuidSchema,
    quantity: positiveIntSchema
  })).min(1)
});

// Validation helper function
export function validateRequest<T>(schema: z.ZodSchema<T>, data: unknown): { success: true; data: T } | { success: false; error: string } {
  try {
    const result = schema.parse(data);
    return { success: true, data: result };
  } catch (error) {
    if (error instanceof z.ZodError) {
      const firstError = error.errors[0];
      return { 
        success: false, 
        error: `${firstError.path.join('.')}: ${firstError.message}` 
      };
    }
    return { success: false, error: 'Invalid request data' };
  }
}

// Sanitization helpers
export function sanitizeString(str: string): string {
  return str.trim().replace(/[<>]/g, '');
}

export function sanitizeEmail(email: string): string {
  return email.trim().toLowerCase();
}

export function sanitizeHtml(html: string): string {
  // Basic HTML sanitization - remove script tags and dangerous attributes
  return html
    .replace(/<script[^>]*>.*?<\/script>/gi, '')
    .replace(/on\w+="[^"]*"/gi, '')
    .replace(/on\w+='[^']*'/gi, '')
    .replace(/javascript:/gi, '');
}