# Customer Migration - Developer Guide

## Overview
This module handles the migration of customers from Magento 2 to Shopify using a highly optimized, queue-based architecture. It supports large datasets (50k+ customers) via lazy loading and asynchronous processing.

## Architecture

1.  **Dispatch (Extract)**: `MigrateCustomers` command streams records using `cursor()` to minimize memory usage.
2.  **Queue (Load)**: `ProcessCustomerMigration` jobs are pushed to the `customer-migrations` queue.
3.  **Transform**: `CustomerTransformer` converts Magento properties to Shopify Admin GraphQL payload format.
4.  **Service**: `ShopifyService` executes the GraphQL mutation `customerCreate`.

## Key Features

### 1. Robust Address Handling
-   **Loading**: Directly queries `customer_address_entity` using the attribute-based `entity_id`.
-   **Deduplication**: Filters out duplicate historical addresses using a hash (`Address1|Zip|City|FirstName`).
-   **Priority**: Ensures the "Default Billing" or "Default Shipping" address is prioritized and marked correctly in Shopify.
-   **Splitting**: Automatically splits multi-line Magento streets into `address1` and `address2`.

### 2. Custom EAV Attributes
-   **Spouse Name**: Dynamically fetched from `customer_entity_varchar` via `getMagentoAttributeValue`.
-   **Anniversary**: Fetched and formatted from `Y-m-d H:i:s` to `Y-m-d`.
-   **Metafields**: all custom data is stored as `custom` namespace metafields.

### 3. Performance
-   Uses `Illuminate\Support\LazyCollection` (`cursor()`) to stream records.
-   Constant memory usage regardless of dataset size.
-   Configurable concurrency via Laravel Queue Workers.

## Setup & Configuration

### 1. Create Metafield Definitions
Before migrating, register the definitions in Shopify so data is visible.
```bash
php artisan shopify:create-metafields
```

### 2. Run Migration
**Option A: Production (All Customers)**
```bash
php artisan migrate:customers
```

**Option B: Testing (Small Batch)**
```bash
php artisan migrate:customers --limit=10
```

### 3. Process Queue
Start the worker to process the jobs.
```bash
php artisan queue:work --queue=customer-migrations --tries=3 --timeout=60
```

## Debugging

### Test Single Customer
Isolate transformation logic without sending to Shopify.
```bash
php artisan test:customer <MAGENTO_ID>
```
Output includes JSON payload and raw DB address data.

### Common Issues
-   **Addresses Missing**: Check `customer_address_entity` parent_id. The transformer uses `$attributes['entity_id']` for reliability.
-   **API Limits**: The standard queue worker processes sequentially. If you hit limits, ShopifyService handles 429 retries, but you can also use `--rest` parameter on queue work to slow down.

## File Structure
-   **Command**: `app/Console/Commands/MigrateCustomers.php`
-   **Job**: `app/Jobs/ProcessCustomerMigration.php`
-   **Transformer**: `app/Services/CustomerTransformer.php`
-   **Service**: `app/Services/ShopifyService.php`
