# Aicoso Wishlist for WooCommerce - Technical Architecture

## Overview

This document defines the technical architecture, database schema, API design, and implementation details for the Aicoso Wishlist for WooCommerce plugin. It serves as the technical blueprint for development teams.

## System Architecture

### High-Level Architecture

```mermaid
graph TB
    subgraph "WordPress/WooCommerce"
        WP[WordPress Core]
        WC[WooCommerce]
        DB[(WordPress Database)]
    end
    
    subgraph "Aicoso Wishlist Plugin"
        CORE[Plugin Core]
        API[REST API]
        ADMIN[Admin Interface]
        PUBLIC[Public Frontend]
        AJAX[AJAX Handlers]
        EMAIL[Email System]
        HOOKS[WordPress Hooks]
    end
    
    subgraph "External Services"
        CACHE[Cache Layer]
        CDN[Content Delivery Network]
        SMTP[SMTP Service]
        SOCIAL[Social Media APIs]
    end
    
    WP --> CORE
    WC --> CORE
    CORE --> DB
    CORE --> API
    CORE --> ADMIN
    CORE --> PUBLIC
    CORE --> AJAX
    CORE --> EMAIL
    CORE --> HOOKS
    
    CACHE --> CORE
    CDN --> PUBLIC
    SMTP --> EMAIL
    SOCIAL --> PUBLIC
```

### Plugin Structure

```
aicoso-wishlist/
├── aicoso-wishlist.php                 # Main plugin file
├── uninstall.php                       # Uninstall cleanup
├── README.txt                          # WordPress readme
├── includes/                           # Core functionality
│   ├── class-aicoso-wishlist.php           # Main plugin class
│   ├── class-aicoso-wishlist-activator.php # Activation handler
│   ├── class-aicoso-wishlist-deactivator.php # Deactivation handler
│   ├── class-aicoso-wishlist-loader.php     # Hook loader
│   ├── class-aicoso-wishlist-i18n.php      # Internationalization
│   ├── models/                             # Data models
│   │   ├── class-wishlist.php
│   │   ├── class-wishlist-item.php
│   │   ├── class-wishlist-share.php
│   │   └── class-wishlist-analytics.php
│   ├── controllers/                        # Business logic
│   │   ├── class-wishlist-controller.php
│   │   ├── class-user-controller.php
│   │   ├── class-product-controller.php
│   │   └── class-email-controller.php
│   ├── database/                           # Database operations
│   │   ├── class-database-manager.php
│   │   ├── class-wishlist-repository.php
│   │   ├── class-analytics-repository.php
│   │   └── migrations/
│   ├── api/                               # REST API
│   │   ├── class-api-manager.php
│   │   ├── class-wishlist-api.php
│   │   └── class-analytics-api.php
│   ├── integrations/                      # Third-party integrations
│   │   ├── class-woocommerce-integration.php
│   │   ├── class-cache-integration.php
│   │   └── class-wpml-integration.php
│   ├── utils/                             # Utility classes
│   │   ├── class-security-utils.php
│   │   ├── class-validation-utils.php
│   │   └── class-template-utils.php
│   └── traits/                            # Reusable code
│       ├── trait-singleton.php
│       └── trait-ajax-handler.php
├── admin/                                 # Admin interface
│   ├── class-aicoso-wishlist-admin.php       # Admin main class
│   ├── partials/                              # Admin templates
│   │   ├── aicoso-wishlist-admin-display.php
│   │   ├── aicoso-wishlist-settings-page.php
│   │   └── aicoso-wishlist-analytics-page.php
│   ├── js/                                    # Admin JavaScript
│   │   ├── aicoso-wishlist-admin.js
│   │   └── aicoso-wishlist-settings.js
│   └── css/                                   # Admin styles
│       └── aicoso-wishlist-admin.css
├── public/                                # Frontend functionality
│   ├── class-aicoso-wishlist-public.php      # Public main class
│   ├── partials/                              # Frontend templates
│   │   ├── wishlist-page.php
│   │   ├── wishlist-button.php
│   │   ├── wishlist-table.php
│   │   └── wishlist-share.php
│   ├── js/                                    # Frontend JavaScript
│   │   ├── aicoso-wishlist-public.js
│   │   └── aicoso-wishlist-ajax.js
│   └── css/                                   # Frontend styles
│       └── aicoso-wishlist-public.css
├── assets/                                # Static assets
│   ├── images/                               # Icons and graphics
│   │   ├── heart-icon.svg
│   │   ├── star-icon.svg
│   │   └── wishlist-icons.png
│   └── fonts/                                # Custom fonts (if needed)
├── languages/                             # Translation files
│   ├── aicoso-wishlist.pot
│   ├── aicoso-wishlist-en_US.po
│   └── aicoso-wishlist-en_US.mo
└── tests/                                 # Unit and integration tests
    ├── phpunit.xml
    ├── bootstrap.php
    ├── unit/
    │   ├── test-wishlist-model.php
    │   ├── test-wishlist-controller.php
    │   └── test-database-operations.php
    └── integration/
        ├── test-woocommerce-integration.php
        └── test-api-endpoints.php
```

## Database Schema

### Core Tables

#### 1. Wishlists Table (`wp_aicoso_wishlists`)

```sql
CREATE TABLE wp_aicoso_wishlists (
    id BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT,
    user_id BIGINT(20) UNSIGNED DEFAULT NULL,
    session_id VARCHAR(255) DEFAULT NULL,
    name VARCHAR(255) NOT NULL DEFAULT 'My Wishlist',
    slug VARCHAR(255) NOT NULL,
    description TEXT DEFAULT NULL,
    privacy ENUM('private', 'shared', 'public') NOT NULL DEFAULT 'private',
    share_token VARCHAR(64) DEFAULT NULL,
    is_default TINYINT(1) NOT NULL DEFAULT 0,
    created_at DATETIME NOT NULL,
    updated_at DATETIME NOT NULL,
    expires_at DATETIME DEFAULT NULL,
    PRIMARY KEY (id),
    KEY idx_user_id (user_id),
    KEY idx_session_id (session_id),
    KEY idx_share_token (share_token),
    KEY idx_privacy_created (privacy, created_at),
    KEY idx_expires_at (expires_at),
    UNIQUE KEY unique_user_slug (user_id, slug),
    UNIQUE KEY unique_session_slug (session_id, slug)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
```

#### 2. Wishlist Items Table (`wp_aicoso_wishlist_items`)

```sql
CREATE TABLE wp_aicoso_wishlist_items (
    id BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT,
    wishlist_id BIGINT(20) UNSIGNED NOT NULL,
    product_id BIGINT(20) UNSIGNED NOT NULL,
    variation_id BIGINT(20) UNSIGNED DEFAULT NULL,
    quantity INT(11) NOT NULL DEFAULT 1,
    priority INT(11) NOT NULL DEFAULT 0,
    added_at DATETIME NOT NULL,
    updated_at DATETIME NOT NULL,
    meta_data LONGTEXT DEFAULT NULL, -- JSON for additional data
    PRIMARY KEY (id),
    KEY idx_wishlist_id (wishlist_id),
    KEY idx_product_id (product_id),
    KEY idx_variation_id (variation_id),
    KEY idx_added_at (added_at),
    KEY idx_priority (priority),
    UNIQUE KEY unique_wishlist_product (wishlist_id, product_id, variation_id),
    FOREIGN KEY (wishlist_id) REFERENCES wp_aicoso_wishlists(id) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
```

#### 3. Wishlist Analytics Table (`wp_aicoso_wishlist_analytics`)

```sql
CREATE TABLE wp_aicoso_wishlist_analytics (
    id BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT,
    product_id BIGINT(20) UNSIGNED NOT NULL,
    variation_id BIGINT(20) UNSIGNED DEFAULT NULL,
    action_type ENUM('added', 'removed', 'purchased', 'shared') NOT NULL,
    user_id BIGINT(20) UNSIGNED DEFAULT NULL,
    session_id VARCHAR(255) DEFAULT NULL,
    wishlist_id BIGINT(20) UNSIGNED DEFAULT NULL,
    user_agent TEXT DEFAULT NULL,
    ip_address VARCHAR(45) DEFAULT NULL,
    created_at DATETIME NOT NULL,
    PRIMARY KEY (id),
    KEY idx_product_id (product_id),
    KEY idx_variation_id (variation_id),
    KEY idx_action_type (action_type),
    KEY idx_user_id (user_id),
    KEY idx_created_at (created_at),
    KEY idx_product_action_date (product_id, action_type, created_at)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
```

#### 4. Email Notifications Table (`wp_aicoso_wishlist_notifications`)

```sql
CREATE TABLE wp_aicoso_wishlist_notifications (
    id BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT,
    user_id BIGINT(20) UNSIGNED NOT NULL,
    type ENUM('price_drop', 'back_in_stock', 'promotional', 'reminder') NOT NULL,
    product_id BIGINT(20) UNSIGNED NOT NULL,
    variation_id BIGINT(20) UNSIGNED DEFAULT NULL,
    email VARCHAR(255) NOT NULL,
    status ENUM('pending', 'sent', 'failed') NOT NULL DEFAULT 'pending',
    scheduled_at DATETIME DEFAULT NULL,
    sent_at DATETIME DEFAULT NULL,
    data LONGTEXT DEFAULT NULL, -- JSON for notification data
    created_at DATETIME NOT NULL,
    updated_at DATETIME NOT NULL,
    PRIMARY KEY (id),
    KEY idx_user_id (user_id),
    KEY idx_type (type),
    KEY idx_product_id (product_id),
    KEY idx_status (status),
    KEY idx_scheduled_at (scheduled_at)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
```

### Database Indexes Strategy

```sql
-- Composite indexes for common queries
CREATE INDEX idx_wishlist_user_privacy ON wp_aicoso_wishlists (user_id, privacy);
CREATE INDEX idx_wishlist_items_product_date ON wp_aicoso_wishlist_items (product_id, added_at);
CREATE INDEX idx_analytics_product_action_date ON wp_aicoso_wishlist_analytics (product_id, action_type, created_at);

-- Indexes for search functionality
CREATE FULLTEXT INDEX idx_wishlist_name_description ON wp_aicoso_wishlists (name, description);

-- Indexes for cleanup operations
CREATE INDEX idx_expired_wishlists ON wp_aicoso_wishlists (expires_at) WHERE expires_at IS NOT NULL;
```

## API Design

### REST API Endpoints

#### Authentication
All API endpoints use WordPress REST API authentication methods:
- Cookie authentication for logged-in users
- Application passwords for programmatic access
- Nonce verification for AJAX requests

#### Wishlist Endpoints

**GET /wp-json/aicoso-wishlist/v1/wishlists**
```json
{
  "method": "GET",
  "description": "Get user's wishlists",
  "parameters": {
    "user_id": "int (optional, defaults to current user)",
    "privacy": "string (optional: private, shared, public)",
    "per_page": "int (default: 10, max: 100)",
    "page": "int (default: 1)"
  },
  "response": {
    "wishlists": [
      {
        "id": 123,
        "name": "My Wishlist",
        "slug": "my-wishlist",
        "description": "Items I want",
        "privacy": "private",
        "item_count": 5,
        "share_url": "https://store.com/wishlist/abc123",
        "created_at": "2024-01-01T12:00:00",
        "updated_at": "2024-01-15T10:30:00"
      }
    ],
    "total": 1,
    "total_pages": 1
  }
}
```

**POST /wp-json/aicoso-wishlist/v1/wishlists**
```json
{
  "method": "POST",
  "description": "Create new wishlist",
  "parameters": {
    "name": "string (required, max 255 chars)",
    "description": "string (optional, max 1000 chars)",
    "privacy": "string (optional: private, shared, public, default: private)"
  },
  "response": {
    "id": 124,
    "name": "Birthday Gifts",
    "slug": "birthday-gifts",
    "description": "Items for my birthday",
    "privacy": "shared",
    "share_token": "abc123def456",
    "share_url": "https://store.com/wishlist/abc123def456",
    "created_at": "2024-01-20T14:00:00"
  }
}
```

**GET /wp-json/aicoso-wishlist/v1/wishlists/{id}/items**
```json
{
  "method": "GET",
  "description": "Get wishlist items",
  "parameters": {
    "per_page": "int (default: 20, max: 100)",
    "page": "int (default: 1)",
    "orderby": "string (added_at, priority, name, price)",
    "order": "string (asc, desc)"
  },
  "response": {
    "items": [
      {
        "id": 456,
        "product_id": 789,
        "variation_id": null,
        "quantity": 1,
        "priority": 0,
        "added_at": "2024-01-15T10:30:00",
        "product": {
          "id": 789,
          "name": "Sample Product",
          "slug": "sample-product",
          "price": "$25.00",
          "regular_price": "$30.00",
          "sale_price": "$25.00",
          "on_sale": true,
          "in_stock": true,
          "stock_quantity": 10,
          "images": [
            {
              "id": 101,
              "src": "https://store.com/image.jpg",
              "alt": "Product image"
            }
          ],
          "permalink": "https://store.com/product/sample-product"
        }
      }
    ],
    "total": 5,
    "total_pages": 1
  }
}
```

**POST /wp-json/aicoso-wishlist/v1/wishlists/{id}/items**
```json
{
  "method": "POST",
  "description": "Add item to wishlist",
  "parameters": {
    "product_id": "int (required)",
    "variation_id": "int (optional)",
    "quantity": "int (optional, default: 1)"
  },
  "response": {
    "message": "Product added to wishlist",
    "item": {
      "id": 457,
      "product_id": 790,
      "variation_id": null,
      "quantity": 1,
      "added_at": "2024-01-20T15:00:00"
    }
  }
}
```

#### Analytics Endpoints

**GET /wp-json/aicoso-wishlist/v1/analytics/popular-products**
```json
{
  "method": "GET",
  "description": "Get popular products by wishlist additions",
  "permissions": "manage_woocommerce",
  "parameters": {
    "period": "string (week, month, quarter, year, all)",
    "limit": "int (default: 10, max: 100)"
  },
  "response": {
    "products": [
      {
        "product_id": 789,
        "product_name": "Sample Product",
        "wishlist_count": 25,
        "last_added": "2024-01-20T15:00:00"
      }
    ]
  }
}
```

### AJAX Endpoints

#### Frontend AJAX Actions

**Action: aicoso_add_to_wishlist**
```javascript
// Request
{
  action: 'aicoso_add_to_wishlist',
  product_id: 123,
  variation_id: null, // optional
  quantity: 1,
  wishlist_id: null, // optional, uses default if not specified
  nonce: 'abc123def456'
}

// Response
{
  success: true,
  data: {
    message: 'Product added to wishlist',
    wishlist_count: 5,
    button_text: 'Remove from Wishlist',
    in_wishlist: true
  }
}
```

**Action: aicoso_remove_from_wishlist**
```javascript
// Request
{
  action: 'aicoso_remove_from_wishlist',
  product_id: 123,
  variation_id: null, // optional
  wishlist_id: null, // optional
  nonce: 'abc123def456'
}

// Response
{
  success: true,
  data: {
    message: 'Product removed from wishlist',
    wishlist_count: 4,
    button_text: 'Add to Wishlist',
    in_wishlist: false
  }
}
```

## Security Implementation

### Input Validation and Sanitization

```php
class Security_Utils {
    
    /**
     * Sanitize wishlist name
     */
    public static function sanitize_wishlist_name($name) {
        return sanitize_text_field(wp_strip_all_tags(trim($name)));
    }
    
    /**
     * Validate product ID
     */
    public static function validate_product_id($product_id) {
        $product_id = absint($product_id);
        if (!$product_id || !wc_get_product($product_id)) {
            throw new InvalidArgumentException('Invalid product ID');
        }
        return $product_id;
    }
    
    /**
     * Verify user permissions for wishlist access
     */
    public static function verify_wishlist_access($wishlist_id, $action = 'read') {
        $wishlist = Wishlist::find($wishlist_id);
        if (!$wishlist) {
            throw new Exception('Wishlist not found');
        }
        
        $current_user = wp_get_current_user();
        
        switch ($action) {
            case 'read':
                return $wishlist->is_accessible_by_user($current_user);
            case 'write':
            case 'delete':
                return $wishlist->is_owned_by_user($current_user);
            default:
                return false;
        }
    }
}
```

### SQL Injection Prevention

```php
class Wishlist_Repository {
    
    private $wpdb;
    
    public function __construct() {
        global $wpdb;
        $this->wpdb = $wpdb;
    }
    
    /**
     * Get wishlists with prepared statements
     */
    public function get_user_wishlists($user_id, $privacy = null) {
        $sql = "SELECT * FROM {$this->wpdb->prefix}aicoso_wishlists WHERE user_id = %d";
        $params = [$user_id];
        
        if ($privacy) {
            $sql .= " AND privacy = %s";
            $params[] = $privacy;
        }
        
        $sql .= " ORDER BY created_at DESC";
        
        return $this->wpdb->get_results(
            $this->wpdb->prepare($sql, ...$params)
        );
    }
}
```

### CSRF Protection

```php
class Wishlist_Controller {
    
    /**
     * Add item to wishlist with nonce verification
     */
    public function ajax_add_to_wishlist() {
        // Verify nonce
        if (!wp_verify_nonce($_POST['nonce'], 'aicoso_wishlist_nonce')) {
            wp_die('Security check failed');
        }
        
        // Sanitize inputs
        $product_id = Security_Utils::validate_product_id($_POST['product_id']);
        $variation_id = isset($_POST['variation_id']) ? absint($_POST['variation_id']) : null;
        $quantity = isset($_POST['quantity']) ? absint($_POST['quantity']) : 1;
        
        // Process request
        try {
            $result = $this->add_to_wishlist($product_id, $variation_id, $quantity);
            wp_send_json_success($result);
        } catch (Exception $e) {
            wp_send_json_error($e->getMessage());
        }
    }
}
```

## Performance Optimization

### Database Optimization

#### Query Optimization
```php
class Wishlist_Repository {
    
    /**
     * Get wishlist items with product data in single query
     */
    public function get_wishlist_items_with_products($wishlist_id) {
        $sql = "
            SELECT 
                wi.id, wi.product_id, wi.variation_id, wi.quantity, wi.added_at,
                p.post_title as product_name,
                pm_regular_price.meta_value as regular_price,
                pm_sale_price.meta_value as sale_price,
                pm_stock.meta_value as stock_quantity,
                pm_stock_status.meta_value as stock_status
            FROM {$this->wpdb->prefix}aicoso_wishlist_items wi
            LEFT JOIN {$this->wpdb->posts} p ON wi.product_id = p.ID
            LEFT JOIN {$this->wpdb->postmeta} pm_regular_price 
                ON wi.product_id = pm_regular_price.post_id 
                AND pm_regular_price.meta_key = '_regular_price'
            LEFT JOIN {$this->wpdb->postmeta} pm_sale_price 
                ON wi.product_id = pm_sale_price.post_id 
                AND pm_sale_price.meta_key = '_sale_price'
            LEFT JOIN {$this->wpdb->postmeta} pm_stock 
                ON wi.product_id = pm_stock.post_id 
                AND pm_stock.meta_key = '_stock'
            LEFT JOIN {$this->wpdb->postmeta} pm_stock_status 
                ON wi.product_id = pm_stock_status.post_id 
                AND pm_stock_status.meta_key = '_stock_status'
            WHERE wi.wishlist_id = %d
            ORDER BY wi.added_at DESC
        ";
        
        return $this->wpdb->get_results(
            $this->wpdb->prepare($sql, $wishlist_id)
        );
    }
}
```

#### Caching Strategy
```php
class Cache_Manager {
    
    private $cache_group = 'aicoso_wishlist';
    private $cache_expiration = 3600; // 1 hour
    
    /**
     * Get cached wishlist data
     */
    public function get_wishlist($wishlist_id) {
        $cache_key = "wishlist_{$wishlist_id}";
        $cached = wp_cache_get($cache_key, $this->cache_group);
        
        if (false === $cached) {
            $wishlist = Wishlist::find($wishlist_id);
            if ($wishlist) {
                wp_cache_set($cache_key, $wishlist, $this->cache_group, $this->cache_expiration);
            }
            return $wishlist;
        }
        
        return $cached;
    }
    
    /**
     * Invalidate wishlist cache
     */
    public function invalidate_wishlist($wishlist_id) {
        $cache_key = "wishlist_{$wishlist_id}";
        wp_cache_delete($cache_key, $this->cache_group);
        
        // Also invalidate related caches
        $user_cache_key = "user_wishlists_{$wishlist->user_id}";
        wp_cache_delete($user_cache_key, $this->cache_group);
    }
}
```

### Frontend Performance

#### JavaScript Optimization
```javascript
// Debounced AJAX requests to prevent spam
class WishlistManager {
    
    constructor() {
        this.ajaxQueue = new Map();
        this.debounceTime = 300;
    }
    
    addToWishlist(productId, variationId = null) {
        const key = `${productId}_${variationId || 'null'}`;
        
        // Cancel previous request for same product
        if (this.ajaxQueue.has(key)) {
            this.ajaxQueue.get(key).abort();
        }
        
        // Debounce the request
        clearTimeout(this.debounceTimer);
        this.debounceTimer = setTimeout(() => {
            this.performAddToWishlist(productId, variationId, key);
        }, this.debounceTime);
    }
    
    performAddToWishlist(productId, variationId, key) {
        const xhr = jQuery.ajax({
            url: aicoso_ajax.url,
            type: 'POST',
            data: {
                action: 'aicoso_add_to_wishlist',
                product_id: productId,
                variation_id: variationId,
                nonce: aicoso_ajax.nonce
            },
            success: (response) => {
                this.handleSuccess(response, productId);
                this.ajaxQueue.delete(key);
            },
            error: (xhr, status, error) => {
                this.handleError(error, productId);
                this.ajaxQueue.delete(key);
            }
        });
        
        this.ajaxQueue.set(key, xhr);
    }
}
```

## Integration Architecture

### WooCommerce Integration

#### Hook Integration Points
```php
class WooCommerce_Integration {
    
    public function __construct() {
        // Product page integration
        add_action('woocommerce_single_product_summary', [$this, 'add_wishlist_button'], 25);
        
        // Shop page integration
        add_action('woocommerce_after_shop_loop_item', [$this, 'add_shop_wishlist_button'], 15);
        
        // My Account integration
        add_filter('woocommerce_account_menu_items', [$this, 'add_wishlist_tab']);
        add_action('woocommerce_account_wishlists_endpoint', [$this, 'wishlist_endpoint_content']);
        
        // Cart integration
        add_action('woocommerce_add_to_cart', [$this, 'maybe_remove_from_wishlist'], 10, 6);
        
        // Order integration
        add_action('woocommerce_thankyou', [$this, 'process_order_wishlist_items']);
    }
    
    /**
     * Add wishlist button to product page
     */
    public function add_wishlist_button() {
        if (!$this->should_show_button()) {
            return;
        }
        
        global $product;
        echo $this->render_wishlist_button($product->get_id());
    }
    
    /**
     * Handle item removal when added to cart
     */
    public function maybe_remove_from_wishlist($cart_item_key, $product_id, $quantity, $variation_id, $variation, $cart_item_data) {
        if (get_option('aicoso_remove_after_add_to_cart', 'no') === 'yes') {
            $wishlist_controller = new Wishlist_Controller();
            $wishlist_controller->remove_product_from_all_wishlists($product_id, $variation_id);
        }
    }
}
```

### Third-Party Plugin Compatibility

#### Cache Plugin Integration
```php
class Cache_Integration {
    
    public function __construct() {
        // WP Rocket integration
        add_filter('rocket_exclude_defer_js', [$this, 'exclude_critical_js']);
        add_filter('rocket_excluded_inline_js_content', [$this, 'exclude_inline_js']);
        
        // W3 Total Cache integration
        add_filter('w3tc_can_cache', [$this, 'maybe_disable_page_cache']);
        
        // WP Super Cache integration
        add_action('wp_super_cache_post_cache_age', [$this, 'adjust_cache_age']);
    }
    
    /**
     * Exclude critical wishlist JS from defer
     */
    public function exclude_critical_js($excluded_files) {
        $excluded_files[] = 'aicoso-wishlist-critical';
        return $excluded_files;
    }
    
    /**
     * Disable page caching for dynamic wishlist pages
     */
    public function maybe_disable_page_cache($can_cache) {
        if (is_page() && $this->is_wishlist_page()) {
            return false;
        }
        return $can_cache;
    }
}
```

## Testing Strategy

### Unit Testing

#### Model Testing
```php
class Test_Wishlist_Model extends WP_UnitTestCase {
    
    protected $wishlist;
    protected $user_id;
    
    public function setUp() {
        parent::setUp();
        $this->user_id = $this->factory->user->create();
        $this->wishlist = new Wishlist();
    }
    
    public function test_create_wishlist() {
        $wishlist_data = [
            'user_id' => $this->user_id,
            'name' => 'Test Wishlist',
            'privacy' => 'private'
        ];
        
        $wishlist = Wishlist::create($wishlist_data);
        
        $this->assertInstanceOf(Wishlist::class, $wishlist);
        $this->assertEquals('Test Wishlist', $wishlist->name);
        $this->assertEquals('private', $wishlist->privacy);
        $this->assertTrue($wishlist->id > 0);
    }
    
    public function test_add_product_to_wishlist() {
        $product_id = $this->factory->post->create(['post_type' => 'product']);
        
        $result = $this->wishlist->add_product($product_id);
        
        $this->assertTrue($result);
        $this->assertEquals(1, $this->wishlist->get_item_count());
        $this->assertTrue($this->wishlist->has_product($product_id));
    }
}
```

#### Integration Testing
```php
class Test_WooCommerce_Integration extends WC_Unit_Test_Case {
    
    public function test_wishlist_button_appears_on_product_page() {
        $product = WC_Helper_Product::create_simple_product();
        
        // Simulate product page
        global $woocommerce, $post, $product as global_product;
        $post = get_post($product->get_id());
        $global_product = $product;
        
        // Capture output
        ob_start();
        do_action('woocommerce_single_product_summary');
        $output = ob_get_clean();
        
        $this->assertContains('aicoso-wishlist-button', $output);
        $this->assertContains('Add to Wishlist', $output);
    }
}
```

### Performance Testing

#### Load Testing Script
```php
class Performance_Test {
    
    public function test_wishlist_creation_performance() {
        $start_time = microtime(true);
        $memory_start = memory_get_usage(true);
        
        // Create 1000 wishlists
        for ($i = 0; $i < 1000; $i++) {
            $user_id = $this->factory->user->create();
            Wishlist::create([
                'user_id' => $user_id,
                'name' => "Test Wishlist {$i}",
                'privacy' => 'private'
            ]);
        }
        
        $execution_time = microtime(true) - $start_time;
        $memory_usage = memory_get_usage(true) - $memory_start;
        
        // Assert performance thresholds
        $this->assertLessThan(5.0, $execution_time, 'Wishlist creation took too long');
        $this->assertLessThan(50 * 1024 * 1024, $memory_usage, 'Memory usage too high');
    }
}
```

## Deployment Architecture

### Environment Configuration

#### Production Environment
```php
// wp-config.php additions for production
define('AICOSO_WISHLIST_ENV', 'production');
define('AICOSO_WISHLIST_DEBUG', false);
define('AICOSO_WISHLIST_CACHE_ENABLED', true);
define('AICOSO_WISHLIST_DB_OPTIMIZE', true);
```

#### Staging Environment
```php
// wp-config.php additions for staging
define('AICOSO_WISHLIST_ENV', 'staging');
define('AICOSO_WISHLIST_DEBUG', true);
define('AICOSO_WISHLIST_CACHE_ENABLED', false);
define('AICOSO_WISHLIST_TEST_MODE', true);
```

### Database Migration System

```php
class Database_Manager {
    
    private $migrations_path;
    private $current_version;
    
    public function __construct() {
        $this->migrations_path = plugin_dir_path(__FILE__) . 'migrations/';
        $this->current_version = get_option('aicoso_wishlist_db_version', '0.0.0');
    }
    
    /**
     * Run pending migrations
     */
    public function migrate() {
        $target_version = AICOSO_WISHLIST_VERSION;
        $migrations = $this->get_pending_migrations($target_version);
        
        foreach ($migrations as $migration) {
            $this->run_migration($migration);
        }
        
        update_option('aicoso_wishlist_db_version', $target_version);
    }
    
    /**
     * Run a single migration
     */
    private function run_migration($migration_file) {
        require_once $this->migrations_path . $migration_file;
        
        $class_name = $this->get_migration_class_name($migration_file);
        $migration = new $class_name();
        $migration->up();
    }
}
```

## Monitoring and Analytics

### Error Logging
```php
class Error_Logger {
    
    private $log_file;
    
    public function __construct() {
        $upload_dir = wp_upload_dir();
        $this->log_file = $upload_dir['basedir'] . '/aicoso-wishlist-errors.log';
    }
    
    /**
     * Log error with context
     */
    public function log_error($message, $context = []) {
        if (!AICOSO_WISHLIST_DEBUG) {
            return;
        }
        
        $entry = [
            'timestamp' => current_time('mysql'),
            'level' => 'ERROR',
            'message' => $message,
            'context' => $context,
            'trace' => debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 5)
        ];
        
        error_log(json_encode($entry) . PHP_EOL, 3, $this->log_file);
    }
}
```

### Performance Monitoring
```php
class Performance_Monitor {
    
    private $timers = [];
    
    public function start_timer($name) {
        $this->timers[$name] = [
            'start' => microtime(true),
            'memory_start' => memory_get_usage(true)
        ];
    }
    
    public function end_timer($name) {
        if (!isset($this->timers[$name])) {
            return null;
        }
        
        $timer = $this->timers[$name];
        $execution_time = microtime(true) - $timer['start'];
        $memory_usage = memory_get_usage(true) - $timer['memory_start'];
        
        // Log if execution time is too high
        if ($execution_time > 1.0) {
            error_log("Slow operation detected: {$name} took {$execution_time}s");
        }
        
        unset($this->timers[$name]);
        
        return [
            'execution_time' => $execution_time,
            'memory_usage' => $memory_usage
        ];
    }
}
```

---

**Document Version:** 1.0  
**Last Updated:** August 2024  
**Next Review:** Before development phase begins