# Schema and Type Validation Testing TODOs

## Overview
Critical gaps in runtime validation, edge case handling, and type safety verification for data schemas and types.

---

## 🔴 High Priority Items

### schemas-runtime-001: Create Zod schemas for types/cart.ts and types/product.ts with runtime validation
**File Location**: `schemas/cart.ts` and `schemas/product.ts` (new files)
**Current State**: Pure TypeScript types with no runtime validation
**Impact**: Critical - Invalid data could corrupt application state
**Estimated Effort**: 24 hours

**Specific Tasks**:

#### Cart Schema Implementation
- [ ] Create CartItemSchema with runtime validation
- [ ] Create CartSchema with total calculations
- [ ] Add quantity validation (min/max limits)
- [ ] Add product reference validation
- [ ] Add cart currency validation
- [ ] Create cart transformation functions

#### Product Schema Implementation
- [ ] Create ProductSchema with all fields
- [ ] Create ProductVariantSchema for variants
- [ ] Create ProductImageSchema for images
- [ ] Add price validation (positive numbers, currency format)
- [ ] Add inventory validation (non-negative integers)
- [ ] Add product category validation

#### Runtime Validation Integration
- [ ] Integrate schemas with action functions
- [ ] Add form validation for product/cart inputs
- [ ] Create error message localization
- [ ] Add validation to API endpoints
- [ ] Create schema-to-type mapping verification

**Schema Implementation Examples**:
```typescript
// schemas/cart.ts
export const CartItemSchema = z.object({
  id: z.string().uuid(),
  productId: z.string().uuid(),
  quantity: z.number().int().min(1).max(99),
  variantId: z.string().uuid().optional(),
  addedAt: z.date(),
  price: z.number().positive(),
});

export const CartSchema = z.object({
  id: z.string().uuid(),
  items: z.array(CartItemSchema),
  total: z.number().nonnegative(),
  currency: z.string().length(3),
  createdAt: z.date(),
  updatedAt: z.date(),
});

// schemas/product.ts
export const ProductSchema = z.object({
  id: z.string().uuid(),
  name: z.string().min(1).max(255),
  description: z.string().optional(),
  price: z.number().positive(),
  currency: z.string().length(3),
  inventory: z.number().int().nonnegative(),
  images: z.array(ProductImageSchema),
  variants: z.array(ProductVariantSchema).optional(),
  categoryId: z.string().uuid(),
  createdAt: z.date(),
  updatedAt: z.date(),
});
```

**Test Cases Needed**:
```typescript
describe('Runtime Schema Validation', () => {
  describe('Cart Schema', () => {
    test('should validate valid cart items');
    test('should reject invalid quantities');
    test('should validate price format');
    test('should calculate totals correctly');
  });

  describe('Product Schema', () => {
    test('should validate product data');
    test('should enforce price positivity');
    test('should validate inventory numbers');
    test('should require valid UUIDs');
  });
});
```

---

## 🟡 High Priority Items

### schemas-edgecase-001: Add comprehensive edge case testing for all existing schemas
**File Location**: Multiple schema test files (enhance existing)
**Current State**: Basic validation only, missing edge cases
**Impact**: High - Edge cases could crash application
**Estimated Effort**: 32 hours

**Specific Tasks**:

#### Email Validation Edge Cases
- [ ] Test international email formats
- [ ] Test email subdomains
- [ ] Test email plus addressing
- [ ] Test email length limits
- [ ] Test Unicode characters in emails
- [ ] Test malformed email formats

#### UUID Validation Edge Cases
- [ ] Test different UUID versions
- [ ] Test malformed UUID strings
- [ ] Test UUID case sensitivity
- [ ] Test empty UUID strings
- [ ] Test UUID length validation

#### Number Validation Edge Cases
- [ ] Test floating-point precision limits
- [ ] Test negative numbers where inappropriate
- [ ] Test extremely large numbers
- [ ] Test decimal overflow scenarios
- [ ] Test NaN and Infinity handling
- [ ] Test number format validation

#### Date/Time Edge Cases
- [ ] Test invalid date objects
- [ ] Test timezone edge cases
- [ ] Test leap year handling
- [ ] Test date format consistency
- [ ] Test date boundary conditions

#### String Validation Edge Cases
- [ ] Test empty strings vs null
- [ ] Test extremely long strings
- [ ] Test Unicode and special characters
- [ ] Test SQL injection attempts
- [ ] Test XSS injection attempts
- [ ] Test encoding bypass attempts

**Edge Case Test Framework**:
```typescript
describe('Schema Edge Cases', () => {
  describe('Email Validation', () => {
    test('should handle international emails');
    test('should validate email subdomains');
    test('should reject malformed emails');
  });

  describe('Number Validation', () => {
    test('should handle decimal precision');
    test('should reject negative prices');
    test('should handle large numbers');
  });

  describe('String Validation', () => {
    test('should handle Unicode characters');
    test('should prevent SQL injection');
    test('should handle very long strings');
  });
});
```

---

### schemas-transformation-001: Implement schema transformation and type safety verification tests
**File Location**: Multiple schema test files (enhance existing)
**Current State**: No transformation testing
**Impact**: High - Data transformation errors could corrupt data
**Estimated Effort**: 20 hours

**Specific Tasks**:

#### Safe/Unsafe Schema Transformation
- [ ] Test UserSchema → SafeUserSchema transformation
- [ ] Test CustomerSchema → SafeCustomerSchema transformation
- [ ] Test field exclusion logic
- [ ] Test data type preservation
- [ ] Test transformation reversibility

#### Schema Composition Testing
- [ ] Test nested schema validation
- [ ] Test schema inheritance patterns
- [ ] Test schema union types
- [ ] Test conditional validation rules
- [ ] Test schema composition errors

#### Type Safety Verification
- [ ] Test TypeScript type inference from schemas
- [ ] Test runtime vs type consistency
- [ ] Test schema-to-type mapping
- [ ] Test type guard functionality
- [ ] Test schema evolution compatibility

**Transformation Test Examples**:
```typescript
describe('Schema Transformations', () => {
  test('should transform UserSchema to SafeUserSchema correctly', () => {
    const user = { id: '123', email: 'test@example.com', password: 'secret' };
    const safeUser = SafeUserSchema.parse(user);
    expect(safeUser).not.toHaveProperty('password');
    expect(safeUser.email).toBe(user.email);
  });

  test('should maintain type safety in transformations', () => {
    // Verify TypeScript types match runtime validation
    const result = ProductSchema.parse(validProductData);
    expectTypeOf(result).toEqualTypeOf<Product>();
  });
});
```

---

## Missing Schema Testing Areas

### Database Schema Alignment
- [ ] Test schema alignment with database structure
- [ ] Test constraint validation (foreign keys, unique constraints)
- [ ] Test data type mapping (PostgreSQL → TypeScript)
- [ ] Test migration compatibility

### API Schema Testing
- [ ] Test request/response schema validation
- [ ] Test API version compatibility
- [ ] Test error response schemas
- [ ] Test pagination schemas

### Frontend Form Integration
- [ ] Test schema-driven form validation
- [ ] Test client-side vs server-side validation consistency
- [ ] Test form error message mapping
- [ ] Test conditional form field validation

---

## Testing Strategy

### Schema Testing Framework
```typescript
describe('SchemaName', () => {
  describe('Basic Validation', () => {
    test('should validate correct data structure');
    test('should reject missing required fields');
    test('should accept optional fields');
  });

  describe('Type Validation', () => {
    test('should validate field types correctly');
    test('should coerce compatible types');
    test('should reject incompatible types');
  });

  describe('Constraint Validation', () => {
    test('should enforce minimum/maximum values');
    test('should enforce length constraints');
    test('should enforce pattern constraints');
  });

  describe('Edge Cases', () => {
    test('should handle boundary values');
    test('should handle special characters');
    test('should handle malformed data');
  });

  describe('Error Messages', () => {
    test('should provide meaningful error messages');
    test('should localize error messages');
    test('should provide field-specific errors');
  });

  describe('Performance', () => {
    test('should validate quickly');
    test('should handle large datasets');
    test('should not have memory leaks');
  });
});
```

### Property-Based Testing
```typescript
// Using fast-check for property-based testing
describe('Property-Based Schema Testing', () => {
  test('should maintain invariants for valid data', () => {
    fc.assert(fc.property(arbitraryValidProduct, (product) => {
      const result = ProductSchema.safeParse(product);
      expect(result.success).toBe(true);
    }));
  });
});
```

---

## Implementation Priorities

### Phase 1: Runtime Validation (Week 1)
1. **Cart Schema** - Immediate data integrity needs
2. **Product Schema** - Core e-commerce data
3. **Basic Integration** - Schema integration with actions

### Phase 2: Edge Case Coverage (Week 2)
4. **Email/UUID Edge Cases** - Common validation issues
5. **Number/String Edge Cases** - Data integrity
6. **Date/Time Edge Cases** - Temporal data safety

### Phase 3: Advanced Features (Week 3)
7. **Schema Transformations** - Safe data handling
8. **Type Safety Verification** - Development confidence
9. **Performance Optimization** - Validation efficiency

---

## Success Metrics

### Schema Validation Targets
- **Runtime Validation Coverage**: 100% of data types
- **Edge Case Coverage**: 95%+ of edge scenarios
- **Type Safety Consistency**: 100% TypeScript ↔ Runtime alignment
- **Validation Performance**: <1ms per validation call
- **Error Message Quality**: 100% meaningful error messages

### Quality Gates
- No unvalidated data entry points
- All API endpoints use schema validation
- All forms have client-side validation
- All database operations validate input

---

## Tools and Libraries

### Schema Validation
- **Zod**: Schema validation (already in use)
- **fast-check**: Property-based testing
- **zod-to-ts**: Type generation from schemas
- **@zod/dev**: Development utilities

### Testing Utilities
- **@faker-js/faker**: Test data generation
- **custom matchers**: Schema-specific assertions
- **test factories**: Consistent test data

---

## Implementation Notes

1. **Validation First**: Implement validation before processing any external data
2. **Defense in Depth**: Validate at multiple layers (client, API, database)
3. **Error Handling**: Provide clear, actionable error messages
4. **Performance Consideration**: Use efficient validation for hot paths
5. **Type Safety**: Ensure runtime validation matches TypeScript types

This comprehensive schema and type validation plan ensures all data entering the system is properly validated, maintaining data integrity and preventing runtime errors.