# CLAUDE.md - Manutenção Telegram Bot

## 🤖 Project Overview

**manutencao-telegram-bot** is the Telegram messaging interface for the Manutenção platform - an "Uber for technical repairs" service. This Node.js bot provides a conversational interface for users to book, manage, and track maintenance appointments through Telegram messaging.

### Core Functionality
- **Multi-user Support**: Serves technicians, service departments, companies, and end users
- **Appointment Management**: Create, reschedule, and cancel maintenance appointments  
- **Equipment Registration**: Add and manage equipment for service requests
- **Intelligent Matching**: Fuzzy search for equipment types and brands
- **Real-time Integration**: Seamless communication with backend API
- **State Management**: Complex conversation flow management

---

## 🏗️ Technical Architecture

### Technology Stack
- **Runtime**: Node.js (v14+)
- **Main Framework**: node-telegram-bot-api (v0.66.0)
- **HTTP Client**: axios (v1.9.0) with HTTPS agent support
- **Fuzzy Matching**: string-similarity (v4.0.4)
- **Environment Management**: dotenv (v16.5.0)
- **Process Management**: PM2 (production)
- **Development**: nodemon (v3.0.0)

### Project Structure
```
manutencao-telegram-bot/
├── index.js                   # Main application entry point
├── apiHelper.js               # Backend API integration
├── apiHelperEquipment.js      # Equipment-specific API operations
├── config/
│   └── constants.js           # Time translations and formatters
├── states/
│   └── stateDefinitions.js    # State machine configuration (25+ states)
├── services/
│   ├── stateManager.js        # State transition management
│   └── userDataManager.js     # User data operations
├── handlers/
│   ├── messageHandler.js      # Text message processing
│   └── callbackHandler.js     # Button callback handling
├── utils/
│   ├── helpers.js             # Utility functions and fuzzy search
│   └── messageUtils.js        # Message formatting utilities
├── scripts/
│   └── bump-version.js        # Version management
├── *.json                     # Equipment and brand data files
└── package.json               # Dependencies and scripts
```

### Key Components

#### 1. **State Machine** (`states/stateDefinitions.js`)
Complex conversation flow with 25+ states including:
- Phone verification states
- Equipment registration flow
- Appointment scheduling states  
- Data correction workflows
- Error handling states

#### 2. **Message Processing** (`handlers/`)
- **Text Handler**: Processes user text input with fuzzy matching
- **Callback Handler**: Manages button interactions and navigation
- **State Transitions**: Handles complex state changes and data validation

#### 3. **API Integration** (`apiHelper.js`)
RESTful integration with backend services:
- User authentication and management
- Equipment CRUD operations
- Appointment lifecycle management
- Address and client data operations
- Slot availability and reservation system

#### 4. **Fuzzy Search System** (`utils/helpers.js`)
Intelligent matching for Portuguese language:
- Equipment type recognition with synonyms
- Brand name variations and abbreviations
- String similarity algorithms for user input tolerance

#### 5. **Data Models**
- **User Data**: Phone, CPF/CNPJ, establishment info
- **Equipment**: Type, brand, model, location, client association
- **Appointments**: Scheduling, status, equipment, address
- **States**: Conversation context, correction flags, selections

---

## 🔧 Environment Configuration

### Required Environment Variables
```bash
TELEGRAM_BOT_TOKEN=your_bot_token_from_botfather
API_BASE_URL=https://your-backend-api-domain.com
SYSTEM_TOKEN=your_backend_auth_token
NODE_ENV=development|production
```

### Development Setup
```bash
npm install
npm run dev        # Start with nodemon
npm start         # Production start
```

### Production Deployment
```bash
pm2 start index.js --name manutencao-bot
pm2 save && pm2 startup
```

---

## 📋 Manual Testing Scenarios

### **PRIMARY USER FLOWS**

#### **Test 1: New User Complete Journey**
**Objective**: Test complete onboarding flow for new user
**Prerequisites**: Use unknown phone number
**Steps**:
1. Start conversation with bot
2. Share phone number (via contact or text)
3. Enter CPF/CNPJ when prompted
4. Enter establishment name
5. Enter establishment address  
6. Select "Yes" to open order
7. Add new equipment type (e.g., "geladeira")
8. Confirm equipment type match
9. Select brand (e.g., "LG" or "Outro")
10. Describe equipment issue
11. Select preferred date/time
12. Enter your name as solicitante
13. Confirm appointment data
14. Confirm final booking

**Expected Outputs**:
- Phone verification → CPF request
- Manual establishment creation
- Equipment type fuzzy matching and confirmation
- Brand selection with custom option
- Date/time selection with availability
- Appointment confirmation message
- "Chamado criado com sucesso!" success message

#### **Test 2: Existing User with Open Appointments**
**Objective**: Test appointment management for existing users
**Prerequisites**: Use phone number with existing appointments
**Steps**:
1. Share known phone number
2. View list of open appointments
3. Select an existing appointment
4. Choose "Reagendar" (Reschedule)
5. Select new date/time
6. Confirm changes
7. Alternatively: Choose "Cancelar" (Cancel)
8. Confirm cancellation

**Expected Outputs**:
- Recognition of existing user
- Display of open appointments with dates/equipment
- Reschedule options with available slots
- "Agendamento atualizado com sucesso!" message
- Or "Seu atendimento foi cancelado" for cancellations

#### **Test 3: Existing User New Appointment**
**Objective**: Test new appointment creation for existing users  
**Prerequisites**: Use phone number with registered equipment but no open appointments
**Steps**:
1. Share known phone number
2. Select existing equipment or "Adicionar novo equipamento"
3. If new equipment: Follow equipment registration flow
4. If existing: Select equipment and describe issue
5. Select date/time
6. Enter solicitante name
7. Confirm appointment data
8. Complete booking

**Expected Outputs**:
- Equipment list display
- Either equipment selection or new equipment flow
- Appointment creation with existing user data
- Success confirmation

#### **Test 4: Technical Department Flow**
**Objective**: Test technical service department user flow
**Prerequisites**: Use CPF/CNPJ of registered establishment
**Steps**:
1. Share phone number
2. Enter CPF/CNPJ when prompted
3. Confirm establishment details
4. Select "Yes" to open technical order
5. Follow equipment and appointment flow

**Expected Outputs**:
- CPF/CNPJ verification
- Establishment confirmation dialog
- Technical order prompt
- Normal appointment flow

#### **Test 5: Equipment-less User Flow**
**Objective**: Test user with no registered equipment
**Prerequisites**: Use phone of user with no equipment
**Steps**:
1. Share known phone number
2. View "Você não tem nenhum equipamento registrado" message
3. Select "Adicionar novo equipamento"
4. Complete equipment registration
5. Continue with appointment booking

**Expected Outputs**:
- "No equipment registered" message
- Add equipment option
- Equipment registration flow
- Appointment completion

#### **Test 6: Multi-appointment Management**
**Objective**: Test user with multiple open appointments
**Prerequisites**: User with 2+ open appointments
**Steps**:
1. Share phone number
2. View list of multiple appointments
3. Select different appointments
4. Test reschedule/cancel options for each
5. Verify correct appointment data display

**Expected Outputs**:
- Multiple appointments listed with correct details
- Each appointment shows proper date/equipment/location
- Individual appointment management
- Correct data association

#### **Test 7: Ghost Technician Mode Testing**
**Objective**: Test availability display with ghost technician on/off
**Prerequisites**: Admin access to toggle ghost technician setting
**Steps**:
1. With ghost mode OFF: Check available time slots
2. Toggle ghost technician ON
3. Check same date range for available slots
4. Compare availability displays
5. Test appointment creation in both modes

**Expected Outputs**:
- Limited slots with ghost mode OFF
- All time slots available with ghost mode ON
- Appropriate slot booking behavior
- Proper availability messaging

#### **Test 8: Returning User Quick Booking**
**Objective**: Test streamlined flow for repeat users
**Prerequisites**: User with previous bookings and registered equipment
**Steps**:
1. Share known phone number
2. Quickly navigate through equipment selection
3. Use existing equipment data
4. Complete appointment booking efficiently
5. Verify data pre-population

**Expected Outputs**:
- Faster navigation through known data
- Pre-populated information where appropriate
- Streamlined confirmation process
- Quick success completion

---

### **EQUIPMENT & SEARCH TESTING**

#### **Test 9: Fuzzy Equipment Matching**
**Objective**: Test intelligent equipment type recognition
**Test Inputs**: 
- "geladeira" (correct)
- "geladeir" (typo)
- "refrigerador" (synonym)
- "freezer" (related)
- "ar condicionado"
- "arcondicionado" (no space)

**Steps**:
1. Start new equipment registration
2. Enter each test input
3. Check fuzzy matching results
4. Verify confirmation dialogs
5. Test acceptance/rejection of matches

**Expected Outputs**:
- Correct equipment type matches despite typos
- Confirmation dialogs: "Este é o equipamento que você selecionou?"
- Proper synonyms recognition
- Fallback to "not found" for unsupported types

#### **Test 10: Brand Selection Flow**  
**Objective**: Test brand selection with predefined and custom options
**Test Data**: LG, Samsung, Electrolux, Brastemp, custom brands
**Steps**:
1. After equipment type selection, view brand options
2. Select predefined brands (LG, Samsung, etc.)
3. Select "Outro" for custom brand
4. Enter custom brand name
5. Test brand confirmation flow

**Expected Outputs**:
- Brand buttons: LG, Samsung, Electrolux, Brastemp, Outro
- Custom brand text input prompt
- Brand confirmation or direct progression
- Proper brand data storage

#### **Test 11: Equipment Type Not Found**
**Objective**: Test handling of unsupported equipment types
**Test Inputs**: "spaceship", "time machine", "quantum computer"
**Steps**:
1. Enter unsupported equipment type
2. Check fuzzy search behavior
3. Verify fallback message
4. Check transfer to human assistance

**Expected Outputs**:
- "Ainda não trabalhamos com esse tipo de equipamento"
- "Vou te direcionar para um assistente" 
- Conversation ends with human transfer

#### **Test 12: Brand Fuzzy Matching**
**Objective**: Test brand name variations and abbreviations
**Test Inputs**: "LG", "lg", "L.G.", brand abbreviations, misspellings
**Steps**:
1. Complete equipment type selection  
2. Test various brand name inputs
3. Check fuzzy matching accuracy
4. Verify custom brand fallbacks

**Expected Outputs**:
- Accurate brand matching for variations
- Fuzzy search tolerance for typos
- Custom brand entry for unknown brands
- Proper brand data handling

#### **Test 13: Equipment Registration**
**Objective**: Test complete new equipment creation
**Steps**:
1. Select "Adicionar novo equipamento"
2. Enter equipment type with fuzzy matching
3. Confirm equipment type
4. Select or enter brand
5. Describe equipment issue
6. Verify equipment creation
7. Check equipment association with user

**Expected Outputs**:
- Equipment created in backend
- Proper client association
- Equipment data stored correctly
- Equipment available for future use

#### **Test 14: Equipment Modification During Correction**
**Objective**: Test equipment changes during appointment correction
**Steps**:
1. Create appointment with equipment
2. Enter data correction flow
3. Modify equipment type and/or brand
4. Check equipment re-creation logic
5. Verify appointment updates

**Expected Outputs**:
- New equipment creation when needed
- Proper appointment equipment association
- Data consistency maintained
- Correction flow completion

---

### **DATE/TIME & AVAILABILITY TESTING**

#### **Test 15: Date Navigation Testing**
**Objective**: Test date selection and navigation controls
**Steps**:
1. Enter date selection state
2. Test "Hoje" (Today) selection
3. Use "Próximo dia ➡️" navigation
4. Use "⬅️ Dia anterior" navigation  
5. Test boundary conditions (day 0 and day 3+)
6. Verify date formatting and labels

**Expected Outputs**:
- Today shows as "Hoje"
- Future days show as "Sexta-feira, 25/08" format
- Navigation buttons appear/disappear correctly
- 4-day booking window enforced
- "Nenhuma destas opções" appears at end

#### **Test 16: Time Slot Selection**
**Objective**: Test time slot selection across different days
**Steps**:
1. For each available day, test:
   - "Manhã" (Morning) selection
   - "Tarde" (Afternoon) selection  
   - "Noite" (Night) selection
2. Verify time slot data storage
3. Check slot reservation functionality

**Expected Outputs**:
- Time slots labeled correctly in Portuguese
- Proper date/time combination storage
- Slot reservation created temporarily
- Correct progression to next state

#### **Test 17: Slot Availability Handling**
**Objective**: Test availability-based slot display
**Prerequisites**: Backend with realistic technician availability
**Steps**:
1. Check slot availability for different days
2. Verify only available slots are shown
3. Test days with no availability
4. Check navigation with mixed availability

**Expected Outputs**:
- Only available time slots displayed as buttons
- Unavailable slots hidden from interface
- Navigation skips days with no availability
- Clear availability messaging

#### **Test 18: Unsuitable Time Flow**
**Objective**: Test "none of these options" pathway
**Steps**:
1. Navigate through all available days
2. Reach end of booking window
3. Select "Nenhuma destas opções"
4. Verify human transfer process

**Expected Outputs**:
- "Nenhuma destas opções" button appears
- "Ok! Estamos transferindo para um atendente" message
- Conversation flow termination
- Human assistance transfer

#### **Test 19: Slot Reservation System**
**Objective**: Test temporary slot holding during booking
**Steps**:
1. Select specific date/time slot
2. Verify slot reservation creation
3. Complete appointment booking
4. Test reservation release on success
5. Test reservation cleanup on failure/timeout

**Expected Outputs**:
- Slot reserved temporarily during booking
- Reservation released after successful booking
- Reservation cleared on booking failure
- No slot conflicts between users

#### **Test 20: Maximum Slots Reached**
**Objective**: Test fully booked time slot handling
**Prerequisites**: Backend with slot limits configured
**Steps**:
1. Attempt to book fully booked time slot
2. Check error message display
3. Verify return to date selection
4. Test alternative slot selection

**Expected Outputs**:
- "Não há mais vagas disponíveis para este horário"
- "Por favor, escolha outro" guidance
- Return to date selection interface
- Ability to select alternative slots

#### **Test 21: Ghost Mode vs Real Availability**
**Objective**: Compare slot display modes
**Steps**:
1. Check availability with ghost technician OFF
2. Note available slots and times
3. Toggle ghost technician ON
4. Compare slot availability display
5. Test booking behavior in both modes

**Expected Outputs**:
- Limited real slots vs. all slots available
- Ghost mode shows 999 technicians available
- Real mode shows actual technician counts
- Appropriate booking success in both modes

---

### **DATA CORRECTION WORKFLOWS**

#### **Test 22: Address Correction Testing**
**Objective**: Test address modification during appointment correction
**Steps**:
1. Create appointment with initial address
2. Enter data correction state
3. Select "Endereço" correction option
4. Enter new address information
5. Verify address update in appointment
6. Complete correction flow

**Expected Outputs**:
- Address correction prompt
- New address text input
- Address API creation or update
- Updated appointment data display
- Successful correction completion

#### **Test 23: Equipment Type Correction**
**Objective**: Test equipment type changes during correction
**Steps**:
1. Create appointment with initial equipment type
2. Enter correction flow
3. Select "Tipo equipamento" option
4. Enter new equipment type
5. Go through brand re-selection
6. Re-describe equipment issue
7. Complete correction

**Expected Outputs**:
- Equipment type modification prompt
- Fuzzy matching for new type
- Required brand re-selection
- Equipment issue re-description
- New equipment creation if needed
- Updated appointment association

#### **Test 24: Brand-Only Correction**
**Objective**: Test brand modification without type change
**Steps**:
1. Create appointment with specific brand
2. Enter correction for brand only
3. Select "Marca" correction option
4. Choose new brand
5. Verify minimal update process
6. Check equipment issue handling

**Expected Outputs**:
- Brand correction prompt
- Brand selection interface
- No equipment issue re-query (minimal change)
- Equipment update or creation as needed
- Streamlined correction flow

#### **Test 25: Name/Solicitante Correction**
**Objective**: Test requestor name changes
**Steps**:
1. Create appointment with initial requestor name
2. Enter correction flow
3. Select "Solicitante" option
4. Enter new requestor name
5. Verify name tracking and updates

**Expected Outputs**:
- Solicitante correction prompt
- Text input for new name
- Original name tracking for comparison
- Change flag setting
- Updated appointment data

#### **Test 26: Date-Only Correction**
**Objective**: Test streamlined date-only modifications
**Steps**:
1. Create appointment with initial date/time
2. Enter correction mode
3. Select "Data" correction option
4. Choose new date/time
5. Verify streamlined confirmation
6. Check minimal update process

**Expected Outputs**:
- Date correction takes directly to date selection
- New date/time selection interface
- Direct confirmation without re-entering other data
- Date change flag tracking
- Efficient appointment update

---

### **ERROR HANDLING & RECOVERY**

#### **Test 27: API Connection Failures**
**Objective**: Test network error handling and recovery
**Test Conditions**: Simulate network issues, timeout backend API
**Steps**:
1. Start conversation during network issues
2. Attempt phone verification with API down
3. Try equipment creation with connection failures
4. Test appointment booking during outages
5. Verify error messages and retry behavior

**Expected Outputs**:
- Clear error messages for users
- Retry mechanisms where appropriate
- Fallback to human assistance when needed
- No conversation state corruption
- Graceful degradation of functionality

#### **Test 28: Invalid Phone Number Handling**
**Objective**: Test phone number validation and error handling
**Test Inputs**: 
- "123" (too short)
- "invalid-phone" (non-numeric)
- Empty input
- International format variations

**Steps**:
1. Attempt phone entry with invalid formats
2. Check validation responses
3. Test re-prompting behavior
4. Verify eventual successful entry

**Expected Outputs**:
- Phone format validation
- Re-prompting for correct format
- Clear guidance on expected format
- Successful progression with valid input
- Contact sharing as alternative

#### **Test 29: CPF/CNPJ Validation**
**Objective**: Test document validation and fallback flows
**Test Inputs**: Invalid CPF/CNPJ formats, non-existent documents
**Steps**:
1. Enter invalid CPF/CNPJ formats
2. Enter valid format but non-existent document
3. Test manual establishment creation fallback
4. Verify user creation process

**Expected Outputs**:
- Document format validation
- "Não encontrei nenhum registro" for unknown documents
- Manual establishment creation prompt
- User creation with manual data
- Successful flow completion

#### **Test 30: Equipment Creation Failures**
**Objective**: Test equipment API failures and handling
**Test Conditions**: Backend equipment creation errors
**Steps**:
1. Attempt equipment creation with API errors
2. Check error message display
3. Verify conversation recovery
4. Test retry mechanisms

**Expected Outputs**:
- "Erro ao criar equipamento" message
- "Por favor, tente novamente mais tarde"
- Conversation state preservation or reset
- Clear user guidance

#### **Test 31: Appointment Booking Failures**  
**Objective**: Test various appointment creation failures
**Test Conditions**: 
- MAX_SLOTS_ATTAINED errors
- Validation failures
- Backend service errors

**Steps**:
1. Attempt booking when slots are full
2. Test with invalid appointment data
3. Simulate backend service failures
4. Check error-specific responses

**Expected Outputs**:
- "Não há mais vagas disponíveis" for full slots
- Return to date selection for slot issues
- "Erro ao criar chamado" for general errors
- "Transferir para atendimento humano" for serious errors
- Appropriate conversation flow handling

#### **Test 32: State Corruption Recovery**
**Objective**: Test invalid state handling and recovery
**Test Conditions**: Invalid state data, corrupted user data
**Steps**:
1. Simulate invalid conversation states
2. Test with corrupted user data
3. Check automatic recovery mechanisms
4. Verify state reset functionality

**Expected Outputs**:
- "⚠️ Estado não encontrado. Reiniciando..." message
- Automatic state reset to phone verification
- User data cleanup
- Fresh conversation start
- No lingering corruption

#### **Test 33: Concurrent User Testing**
**Objective**: Test multiple users simultaneously using bot
**Test Conditions**: Multiple Telegram users interacting concurrently
**Steps**:
1. Start conversations from multiple accounts
2. Progress through different states simultaneously
3. Test data isolation between users
4. Verify no cross-contamination
5. Check individual conversation integrity

**Expected Outputs**:
- Each user maintains separate conversation state
- No data mixing between users
- Independent conversation flows
- Proper user data isolation
- Individual error handling

#### **Test 34: Memory Management**
**Objective**: Test long conversations and memory efficiency
**Test Conditions**: Extended conversation sessions, large data sets
**Steps**:
1. Conduct very long conversation sessions
2. Test with users having many appointments/equipment
3. Check memory usage patterns
4. Verify data cleanup processes

**Expected Outputs**:
- Stable memory usage over time
- Efficient data loading for large datasets
- Proper conversation data cleanup
- No memory leaks
- Sustained performance

#### **Test 35: Timeout Handling**
**Objective**: Test session management and timeout behavior
**Test Conditions**: Long idle periods, conversation timeouts
**Steps**:
1. Start conversation and go idle for extended period
2. Test bot restart during active conversations
3. Check conversation resumption behavior
4. Verify timeout cleanup processes

**Expected Outputs**:
- Appropriate timeout handling
- Clean session termination when needed
- Graceful conversation resumption or reset
- Proper resource cleanup
- Clear timeout messaging if applicable

---

### **SPECIAL COMMANDS & NAVIGATION**

#### **Test 36: Restart Command Testing**
**Objective**: Test restart functionality at various conversation points
**Test Inputs**: "recomeçar", "0"
**Steps**:
1. Start conversation and progress to middle states
2. Send "recomeçar" command
3. Verify complete state reset
4. Test "0" command at different states
5. Check data cleanup and fresh start

**Expected Outputs**:
- Immediate state reset to requestPhone
- User data cleanup
- Fresh conversation start
- "Para começar, por favor, compartilhe seu número de telefone" message
- No residual state data

#### **Test 37: Button vs Text Input**
**Objective**: Test mixed input handling in button states
**Steps**:
1. Reach button-based states (equipment selection, date selection, etc.)
2. Send text input instead of using buttons
3. Check guidance messages
4. Verify button preference enforcement
5. Test eventual correct button usage

**Expected Outputs**:
- "Por favor, use os botões para navegar" message
- No state progression with text in button states
- Button interface remains available
- Proper guidance for user interaction
- Successful progression with button use

#### **Test 38: Contact Sharing Flow**
**Objective**: Test phone number sharing via contact vs text input
**Steps**:
1. Use Telegram contact sharing button
2. Alternatively, type phone number as text
3. Test various phone number formats
4. Verify both input methods work
5. Check data processing consistency

**Expected Outputs**:
- Contact sharing extracts phone number correctly
- Manual text input accepts valid formats
- Consistent phone verification behavior
- Same user lookup process for both methods
- Proper conversation continuation

#### **Test 39: Navigation Edge Cases**
**Objective**: Test unusual navigation patterns and edge cases
**Test Conditions**: Invalid button selections, out-of-order interactions
**Steps**:
1. Test clicking expired or invalid buttons
2. Attempt navigation outside normal flow
3. Check callback query error handling
4. Test rapid button clicking
5. Verify state consistency maintenance

**Expected Outputs**:
- "⚠️ Estado inválido ou interação não suportada" for invalid interactions
- State consistency maintained
- No conversation corruption
- Clear error messaging
- Recovery to valid state when possible

---

### **INTEGRATION TESTING**

#### **Test 40: Backend API Full Integration**
**Objective**: Test complete API integration across all endpoints
**Steps**:
1. Test user lookup by phone: GET /users/clients
2. Test user lookup by CPF: GET /users/clients (with CPF param)
3. Test equipment retrieval: GET /equipment/by-client/{id}
4. Test appointment creation: POST /appointments
5. Test appointment updates: PATCH/PUT /appointments/{id}
6. Test equipment creation: POST /equipment
7. Test address creation: POST /addresses
8. Test appointment cancellation: DELETE /appointments/{id}

**Expected Outputs**:
- All API endpoints respond correctly
- Proper authentication with SYSTEM_TOKEN
- HTTPS agent handles certificates correctly
- Error responses processed appropriately
- Data formatting matches API expectations

#### **Test 41: Phone Lookup Integration**
**Objective**: Test phone number lookup and user identification
**Test Data**: Known and unknown phone numbers
**Steps**:
1. Use phone number registered in system
2. Check user data retrieval and processing
3. Use unknown phone number
4. Verify CPF/CNPJ fallback process
5. Test phone number formatting variations

**Expected Outputs**:
- Known phones return user data immediately
- Unknown phones trigger CPF/CNPJ request
- User data processed correctly for appointments
- Phone formatting handled consistently
- Proper error handling for lookup failures

#### **Test 42: Establishment Verification**
**Objective**: Test CPF/CNPJ lookup and establishment confirmation
**Test Data**: Valid and invalid CPF/CNPJ numbers
**Steps**:
1. Enter valid CPF/CNPJ in system
2. Check establishment data display
3. Test establishment confirmation flow
4. Enter invalid/unknown CPF/CNPJ
5. Verify manual creation fallback

**Expected Outputs**:
- Valid documents show establishment details
- Confirmation dialog with correct data
- Unknown documents trigger manual entry
- Manual establishment creation successful
- Proper data association with user

#### **Test 43: Equipment CRUD Operations**
**Objective**: Test complete equipment lifecycle via API
**Steps**:
1. Create new equipment via bot conversation
2. Retrieve equipment list for user
3. Use existing equipment in appointment
4. Modify equipment during correction flows
5. Verify equipment data consistency

**Expected Outputs**:
- Equipment creation API calls successful
- Equipment data stored with correct associations
- Equipment retrieval displays properly
- Equipment modifications handled correctly
- Data consistency maintained across operations

#### **Test 44: Appointment Lifecycle**
**Objective**: Test complete appointment management via API
**Steps**:
1. Create new appointment through conversation
2. View appointment in pending list
3. Reschedule appointment with updates
4. Cancel appointment
5. Verify appointment status changes

**Expected Outputs**:
- Appointment creation via POST /appointments
- Appointment appears in pending list
- Updates use appropriate PATCH/PUT operations
- Cancellation uses DELETE operation
- Status changes reflected correctly

#### **Test 45: Address Management**
**Objective**: Test address creation and association
**Steps**:
1. Create new user with manual address entry
2. Modify address during correction flow
3. Verify address creation API calls
4. Check address association with appointments
5. Test address validation and formatting

**Expected Outputs**:
- Address creation POST /addresses successful
- Addresses properly associated with users/appointments
- Address corrections trigger appropriate updates
- Default address data (city, state, etc.) applied
- Proper error handling for address failures

#### **Test 46: User Registration Flow**
**Objective**: Test complete new user creation process
**Steps**:
1. Use unknown phone and CPF/CNPJ
2. Complete manual establishment entry
3. Verify user creation API call
4. Check user data storage and retrieval
5. Test user association with subsequent data

**Expected Outputs**:
- User creation API call with correct data
- User data includes phone, CPF, establishment details
- Created user accessible for future conversations
- Proper data associations (equipment, appointments)
- Successful integration with existing flow

#### **Test 47: Ghost Technician Settings**
**Objective**: Test dynamic availability based on backend settings
**Steps**:
1. Check current ghost technician setting
2. Test appointment availability with setting OFF
3. Toggle ghost technician setting ON
4. Compare availability display changes
5. Test booking behavior in both modes

**Expected Outputs**:
- Ghost setting retrieved from backend correctly
- Availability changes based on setting
- All slots shown when ghost mode ON
- Real availability when ghost mode OFF
- Proper booking success in both modes

---

### **PERFORMANCE & LOAD TESTING**

#### **Test 48: High Message Volume**
**Objective**: Test bot performance under rapid message sending
**Test Conditions**: Send messages rapidly in sequence
**Steps**:
1. Send multiple messages quickly in succession
2. Test button clicking in rapid succession
3. Check message processing order
4. Verify no message loss
5. Test conversation state consistency

**Expected Outputs**:
- All messages processed in order
- No message loss or duplication
- State transitions handled correctly
- Bot responses maintain consistency
- No performance degradation

#### **Test 49: Large User Data Handling**
**Objective**: Test performance with users having extensive data
**Test Conditions**: Users with many appointments and equipment
**Steps**:
1. Test user with 10+ registered equipment items
2. Test user with multiple open appointments
3. Check equipment list display performance
4. Verify appointment list handling
5. Test data loading speed

**Expected Outputs**:
- Equipment lists load efficiently
- Appointment lists display correctly
- No timeout issues with large datasets
- UI remains responsive
- Proper pagination or limiting if needed

#### **Test 50: Long-running Conversations**
**Objective**: Test extended conversation sessions
**Test Conditions**: Very long conversation with many state changes
**Steps**:
1. Conduct conversation with many corrections and changes
2. Test memory usage over extended session
3. Check conversation state persistence
4. Verify no memory leaks
5. Test eventual conversation completion

**Expected Outputs**:
- Stable performance throughout long sessions
- Memory usage remains reasonable
- State consistency maintained
- No resource leaks
- Successful conversation completion

#### **Test 51: API Response Time Impact**
**Objective**: Test bot behavior with slow API responses
**Test Conditions**: Simulate slow backend responses
**Steps**:
1. Test conversation with deliberately slow API
2. Check timeout handling for API calls
3. Verify user experience during slow responses
4. Test timeout error messages
5. Check recovery after timeouts

**Expected Outputs**:
- Appropriate timeout handling (120s default)
- User-friendly timeout messages
- Conversation recovery after API issues
- No bot crashes on timeouts
- Clear guidance for users during issues

#### **Test 52: Bot Restart Scenarios**
**Objective**: Test bot restart during active conversations
**Test Conditions**: Restart bot while users are mid-conversation
**Steps**:
1. Start conversations from multiple users
2. Progress to various conversation states
3. Restart bot application
4. Check conversation state recovery
5. Test user experience after restart

**Expected Outputs**:
- Graceful handling of restart scenarios
- Clear communication about restart if needed
- User ability to restart conversations
- No data corruption from restarts
- Proper session cleanup and recovery

---

## 📊 Test Data Requirements

### User Test Data
```json
{
  "knownPhones": ["+5511999999999", "11999999999"],
  "unknownPhones": ["+5511888888888", "11777777777"],
  "validCPF": ["12345678901", "98765432100"],
  "validCNPJ": ["12345678000195", "98765432000100"],
  "invalidDocs": ["123", "invalid", "00000000000"]
}
```

### Equipment Test Data
```json
{
  "equipmentTypes": [
    "geladeira", "geladeir", "refrigerador",
    "ar condicionado", "arcondicionado",
    "freezer", "microondas", "lava louça"
  ],
  "brands": [
    "LG", "Samsung", "Electrolux", "Brastemp",
    "Consul", "Philips", "Custom Brand Name"
  ],
  "unsupportedTypes": ["spaceship", "time machine"]
}
```

### Date/Time Test Scenarios
- Current date/time for "today" testing
- Future dates within 4-day booking window  
- Past dates for boundary testing
- Available vs unavailable time slots
- Fully booked scenarios

### API Mock Responses
- Success responses for all endpoints
- Error responses (404, 400, 500, timeout)
- Edge case data (empty lists, null values)
- Large datasets for performance testing

---

## ✅ Test Execution Guidelines

1. **Setup**: Ensure bot is running with proper environment configuration
2. **Data Preparation**: Prepare test data in backend system as needed
3. **Test Isolation**: Use different phone numbers for different test scenarios
4. **State Cleanup**: Use "recomeçar" command between tests when needed
5. **Documentation**: Record actual outputs vs expected outputs
6. **Error Tracking**: Note any deviations from expected behavior
7. **Performance Monitoring**: Watch for response times and resource usage
8. **Integration Verification**: Confirm backend data changes as expected

---

## 🔍 Common Issues and Troubleshooting

### Connection Issues
- Check TELEGRAM_BOT_TOKEN validity
- Verify API_BASE_URL accessibility  
- Confirm SYSTEM_TOKEN authentication
- Test network connectivity

### State Issues
- Use restart commands to reset state
- Check conversation data in logs
- Verify state transition logic
- Monitor memory usage

### API Issues
- Check backend service status
- Verify endpoint responses
- Monitor API call logs
- Test authentication tokens

### Performance Issues
- Monitor bot response times
- Check memory usage patterns
- Verify database performance
- Test concurrent user loads

---

## 📈 Success Criteria

### Functional Tests
- ✅ All primary user flows complete successfully
- ✅ Equipment and search functionality works accurately  
- ✅ Date/time selection handles availability correctly
- ✅ Data correction workflows function properly
- ✅ Error handling provides appropriate responses
- ✅ Special commands work as designed

### Integration Tests  
- ✅ All API endpoints integrate correctly
- ✅ Data consistency maintained across operations
- ✅ Authentication works properly
- ✅ Error responses handled appropriately

### Performance Tests
- ✅ Bot handles concurrent users without issues
- ✅ Response times remain reasonable under load
- ✅ Memory usage stays stable over time
- ✅ Large datasets process efficiently

### User Experience
- ✅ Conversation flows feel natural and intuitive
- ✅ Error messages are clear and helpful
- ✅ Button interfaces work consistently
- ✅ Data input validation guides users appropriately