# Company Migration Implementation Plan

**Date**: 2025-07-04  
**Status**: 📋 PLANNING COMPLETE  
**Risk Level**: 🔴 HIGH  
**Dependencies**: [`company-migration-analysis.md`](./company-migration-analysis.md)

## Migration Strategy Overview

This document outlines the detailed 4-phase migration strategy to safely remove the Company entity and replace it with the new relationship structure (Operators, PropertyOwners, Manufacturers, Designers) across the ThrillWiki Django application.

## Phase-by-Phase Implementation Plan

### Phase 1: Create New Entities 🏗️
**Duration**: 2-3 days  
**Risk Level**: 🟡 LOW  
**Rollback**: Simple (new entities can be removed)

#### 1.1 Create New Models
```python
# New models to create:
- Operators (replace Company.owner for parks)
- PropertyOwners (new optional relationship for parks)
- Manufacturers (rename/replace Company for rides)
- Designers (already exists, verify structure)
```

#### 1.2 Database Schema Changes
- Create new model files
- Generate initial migrations
- Apply migrations to create new tables
- Verify new table structure

#### 1.3 Admin Interface Setup
- Register new models in Django admin
- Configure admin interfaces for new entities
- Set up basic CRUD operations

#### 1.4 Phase 1 Testing
- Verify new models can be created/edited
- Test admin interfaces
- Confirm database schema is correct
- Run existing test suite (should pass unchanged)

### Phase 2: Data Migration 📊
**Duration**: 3-5 days  
**Risk Level**: 🔴 HIGH  
**Rollback**: Complex (requires data restoration)

#### 2.1 Data Analysis & Mapping
```sql
-- Analyze existing company data:
SELECT 
    company_type,
    COUNT(*) as count,
    usage_context
FROM companies_company 
GROUP BY company_type;
```

#### 2.2 Data Migration Scripts
- **Company → Operators**: Migrate companies used as park owners
- **Company → Manufacturers**: Migrate companies used as ride manufacturers  
- **PropertyOwners = Operators**: Initially set PropertyOwners same as Operators
- **Historical Data**: Migrate pghistory tracking data

#### 2.3 Data Migration Execution
```bash
# Critical sequence:
1. uv run manage.py makemigrations --dry-run  # Preview changes
2. Database backup (MANDATORY)
3. uv run manage.py migrate  # Apply data migration
4. Verify data integrity
5. Test rollback procedures
```

#### 2.4 Data Integrity Verification
- Verify all company records migrated correctly
- Check foreign key relationships maintained
- Validate pghistory data preservation
- Confirm no data loss occurred

### Phase 3: Update Dependencies 🔄
**Duration**: 5-7 days  
**Risk Level**: 🟠 MEDIUM-HIGH  
**Rollback**: Moderate (code changes can be reverted)

#### 3.1 Models Update (Critical First)
**Order**: MUST be completed before views/templates

```python
# parks/models.py updates:
- Replace: company = ForeignKey(Company)
- With: operator = ForeignKey(Operators)
- Add: property_owner = ForeignKey(PropertyOwners, null=True, blank=True)

# rides/models.py updates:
- Replace: company = ForeignKey(Company) 
- With: manufacturer = ForeignKey(Manufacturers, null=True, blank=True)
```

#### 3.2 Views Update
**Dependencies**: Models must be updated first

- Update all company-related views
- Modify query logic for new relationships
- Update context data for templates
- Handle new optional relationships

#### 3.3 Templates Update
**Dependencies**: Views must be updated first

- Update 6+ company templates
- Modify cross-references in park/ride templates
- Update form templates for new relationships
- Ensure responsive design maintained

#### 3.4 Tests Update
**Dependencies**: Models/Views/Templates updated first

- Update 429 lines of company tests
- Modify integration tests
- Update test fixtures and factories
- Add tests for new relationships

#### 3.5 Signals & Search Update
- Update Django signals for new models
- Modify search indexing for new relationships
- Update search templates and views
- Verify search functionality

#### 3.6 Admin Interface Update
- Update admin configurations
- Modify admin templates if customized
- Update admin permissions
- Test admin functionality

### Phase 4: Cleanup 🧹
**Duration**: 2-3 days  
**Risk Level**: 🟡 LOW-MEDIUM  
**Rollback**: Difficult (requires restoration of removed code)

#### 4.1 Remove Companies App
- Remove companies/ directory
- Remove from INSTALLED_APPS
- Remove URL patterns
- Remove imports across codebase

#### 4.2 Remove Company Templates
- Remove templates/companies/ directory
- Remove company-related template tags
- Clean up cross-references
- Update template inheritance

#### 4.3 Documentation Update
- Update API documentation
- Update user documentation
- Update developer documentation
- Update README if needed

#### 4.4 Final Cleanup
- Remove unused imports
- Clean up migration files
- Update requirements if needed
- Final code review

## Critical Order of Operations

### ⚠️ MANDATORY SEQUENCE ⚠️
```
1. Phase 1: Create new entities (safe, reversible)
2. Phase 2: Migrate data (HIGH RISK - backup required)
3. Phase 3: Update dependencies in order:
   a. Models FIRST (foreign keys)
   b. Views SECOND (query logic)
   c. Templates THIRD (display logic)
   d. Tests FOURTH (validation)
   e. Signals/Search FIFTH (integrations)
   f. Admin SIXTH (management interface)
4. Phase 4: Cleanup (remove old code)
```

### 🚫 NEVER DO THESE OUT OF ORDER:
- Never update views before models
- Never update templates before views  
- Never remove Company model before data migration
- Never skip database backups
- Never proceed without testing previous phase

## Database Schema Migration Strategy

### New Relationship Structure
```
Current:
Parks → Company (owner)
Rides → Company (manufacturer)

Target:
Parks → Operators (required, replaces Company.owner)
Parks → PropertyOwners (optional, new concept)
Rides → Manufacturers (optional, replaces Company)
Rides → Designers (optional, exists)
```

### Migration Script Approach
```python
# Data migration pseudocode:
def migrate_companies_to_new_structure(apps, schema_editor):
    Company = apps.get_model('companies', 'Company')
    Operator = apps.get_model('operators', 'Operator')
    Manufacturer = apps.get_model('manufacturers', 'Manufacturer')
    
    # Migrate park owners
    for company in Company.objects.filter(used_as_park_owner=True):
        operator = Operator.objects.create(
            name=company.name,
            # ... other fields
        )
        # Update park references
    
    # Migrate ride manufacturers  
    for company in Company.objects.filter(used_as_manufacturer=True):
        manufacturer = Manufacturer.objects.create(
            name=company.name,
            # ... other fields
        )
        # Update ride references
```

## Testing Strategy

### Phase-by-Phase Testing
```bash
# After each phase:
1. uv run manage.py test  # Full test suite
2. Manual testing of affected functionality
3. Database integrity checks
4. Performance testing if needed
5. Rollback testing (Phase 2 especially)
```

### Critical Test Areas
- **Model Relationships**: Foreign key integrity
- **Data Migration**: No data loss, correct mapping
- **pghistory Integration**: Historical data preserved
- **Search Functionality**: New relationships indexed
- **Admin Interface**: CRUD operations work
- **Template Rendering**: No broken references

## Risk Mitigation Procedures

### Database Safety Protocol
```bash
# MANDATORY before Phase 2:
1. pg_dump thrillwiki_db > backup_pre_migration.sql
2. Test restore procedure: psql thrillwiki_test < backup_pre_migration.sql
3. Document rollback steps
4. Verify backup integrity
```

### Rollback Procedures

#### Phase 1 Rollback (Simple)
```bash
# Remove new models:
uv run manage.py migrate operators zero
uv run manage.py migrate manufacturers zero
# Remove from INSTALLED_APPS
```

#### Phase 2 Rollback (Complex)
```bash
# Restore from backup:
dropdb thrillwiki_db
createdb thrillwiki_db  
psql thrillwiki_db < backup_pre_migration.sql
# Verify data integrity
```

#### Phase 3 Rollback (Moderate)
```bash
# Revert code changes:
git revert <migration_commits>
uv run manage.py migrate  # Revert migrations
# Test functionality
```

## Success Criteria

### Phase 1 Success ✅
- [ ] New models created and functional
- [ ] Admin interfaces working
- [ ] Existing functionality unchanged
- [ ] All tests passing

### Phase 2 Success ✅  
- [ ] All company data migrated correctly
- [ ] No data loss detected
- [ ] pghistory data preserved
- [ ] Foreign key relationships intact
- [ ] Rollback procedures tested

### Phase 3 Success ✅
- [ ] All 300+ company references updated
- [ ] New relationships functional
- [ ] Templates rendering correctly
- [ ] Search functionality working
- [ ] All tests updated and passing

### Phase 4 Success ✅
- [ ] Companies app completely removed
- [ ] No broken references remaining
- [ ] Documentation updated
- [ ] Code cleanup completed

## Timeline Estimate

| Phase | Duration | Dependencies | Risk Level |
|-------|----------|--------------|------------|
| Phase 1 | 2-3 days | None | 🟡 LOW |
| Phase 2 | 3-5 days | Phase 1 complete | 🔴 HIGH |
| Phase 3 | 5-7 days | Phase 2 complete | 🟠 MEDIUM-HIGH |
| Phase 4 | 2-3 days | Phase 3 complete | 🟡 LOW-MEDIUM |
| **Total** | **12-18 days** | Sequential execution | 🔴 HIGH |

## Implementation Readiness

### Prerequisites ✅
- [x] Comprehensive analysis completed
- [x] Migration plan documented
- [x] Risk assessment completed
- [x] Success criteria defined

### Next Steps
- [ ] Set up dedicated migration environment
- [ ] Create detailed migration scripts
- [ ] Establish backup and monitoring procedures
- [ ] Begin Phase 1 implementation

**Recommendation**: Proceed with Phase 1 implementation in dedicated environment with comprehensive testing at each step.