# API Completion Implementation Plan

**Date:** 2024-12-19  
**Status:** Ready for Implementation  
**Current Completion:** 95% (81/85 endpoints)  
**Remaining:** 4 endpoints

---

## Executive Summary

The ARMPO API is **95% complete** with 81 out of 85 endpoints implemented. This document outlines the implementation plan for completing the remaining 4 endpoints to achieve 100% API completion.

### Remaining Endpoints

| # | Endpoint | Priority | Status | Estimated Effort |
|---|----------|----------|--------|-----------------|
| 1 | `POST /auth/forgot-password` | 🔴 High | Stub exists | 2-3 hours |
| 2 | `POST /auth/reset-password` | 🔴 High | Stub exists | 2-3 hours |
| 3 | `GET /users/{id}/activity` | 🟡 Medium | Not started | 4-6 hours |
| 4 | `POST /users/{id}/upload-avatar` | 🟢 Low | May be redundant | 1-2 hours |

**Total Estimated Effort:** 1-2 days

---

## 1. Password Reset Endpoints

### 1.1 POST `/auth/forgot-password`

**Status:** Method exists but incomplete (stub)  
**Location:** `api/app/Http/Controllers/AuthController.php` (line 103)  
**Priority:** 🔴 High

#### Current Implementation
```php
public function forgotPassword(Request $request)
{
    $request->validate([
        'email' => 'required|email',
    ]);

    // Logic for password reset link generation
    // ...

    return response()->json(['message' => 'Password reset link sent'], 200);
}
```

#### Required Implementation

**Step 1: Add Route**
- Add public route in `api/routes/api.php`:
```php
Route::post('/auth/forgot-password', [AuthController::class, 'forgotPassword']);
```

**Step 2: Implement Method**
- Use Laravel's built-in password reset functionality
- Generate password reset token
- Send reset email to user
- Return success response

**Step 3: Email Configuration**
- Configure email service (SMTP/Mailgun/SendGrid)
- Create password reset email template
- Set up email queue if needed

#### Implementation Details

```php
public function forgotPassword(Request $request)
{
    $request->validate([
        'email' => 'required|email|exists:users,email',
    ]);

    $status = Password::sendResetLink(
        $request->only('email')
    );

    if ($status === Password::RESET_LINK_SENT) {
        return $this->successResponse(
            null,
            'Password reset link has been sent to your email address.'
        );
    }

    return $this->errorResponse(
        'Unable to send password reset link. Please try again later.',
        422
    );
}
```

**Dependencies:**
- Laravel Password facade
- Email service configured
- Password reset tokens table (already exists)

**Files to Modify:**
- `api/routes/api.php` - Add route
- `api/app/Http/Controllers/AuthController.php` - Complete implementation
- `api/config/mail.php` - Email configuration (if not done)
- Email template (create if needed)

**Testing Requirements:**
- [ ] Valid email sends reset link
- [ ] Invalid email returns error
- [ ] Email contains reset link
- [ ] Rate limiting works (prevent abuse)
- [ ] Token expires after configured time

**Estimated Time:** 2-3 hours

---

### 1.2 POST `/auth/reset-password`

**Status:** Method exists but incomplete (stub)  
**Location:** `api/app/Http/Controllers/AuthController.php` (line 116)  
**Priority:** 🔴 High

#### Current Implementation
```php
public function resetPassword(Request $request)
{
    $request->validate([
        'token' => 'required|string',
        'email' => 'required|email',
        'password' => 'required|string|min:6|confirmed',
    ]);

    // Logic for password reset
    // ...

    return response()->json(['message' => 'Password reset successful'], 200);
}
```

#### Required Implementation

**Step 1: Add Route**
- Add public route in `api/routes/api.php`:
```php
Route::post('/auth/reset-password', [AuthController::class, 'resetPassword']);
```

**Step 2: Implement Method**
- Validate reset token
- Verify token hasn't expired
- Update user password
- Invalidate token
- Return success response

#### Implementation Details

```php
public function resetPassword(Request $request)
{
    $request->validate([
        'token' => 'required|string',
        'email' => 'required|email|exists:users,email',
        'password' => 'required|string|min:6|confirmed',
    ]);

    $status = Password::reset(
        $request->only('email', 'password', 'password_confirmation', 'token'),
        function ($user, $password) {
            $user->forceFill([
                'password' => Hash::make($password)
            ])->save();

            // Optionally: Revoke all user tokens for security
            $user->tokens()->delete();
        }
    );

    if ($status === Password::PASSWORD_RESET) {
        return $this->successResponse(
            null,
            'Password has been reset successfully.'
        );
    }

    return $this->errorResponse(
        'Invalid or expired reset token.',
        422
    );
}
```

**Dependencies:**
- Laravel Password facade
- Password reset tokens table (already exists)

**Files to Modify:**
- `api/routes/api.php` - Add route
- `api/app/Http/Controllers/AuthController.php` - Complete implementation

**Testing Requirements:**
- [ ] Valid token resets password
- [ ] Invalid token returns error
- [ ] Expired token returns error
- [ ] Password validation works
- [ ] Old tokens are invalidated after reset
- [ ] User can login with new password

**Estimated Time:** 2-3 hours

---

## 2. User Activity Log Endpoint

### 2.1 GET `/users/{id}/activity`

**Status:** Not started  
**Priority:** 🟡 Medium  
**Estimated Effort:** 4-6 hours

#### Required Implementation

**Step 1: Create Activity Log Migration**
- Create migration for `user_activity_logs` table
- Fields: id, user_id, activity_type, description, metadata (JSON), ip_address, user_agent, created_at

**Step 2: Create ActivityLog Model**
- Create `app/Models/UserActivityLog.php`
- Define relationships and fillable fields

**Step 3: Create Activity Log Trait (Optional)**
- Create trait to easily log activities
- Can be used across controllers

**Step 4: Implement Controller Method**
- Add method to `UserController`
- Filter by activity type (optional)
- Paginate results
- Return formatted response

**Step 5: Add Route**
- Add authenticated route

#### Database Schema

```php
Schema::create('user_activity_logs', function (Blueprint $table) {
    $table->id();
    $table->foreignId('user_id')->constrained()->onDelete('cascade');
    $table->string('activity_type'); // login, logout, profile_update, etc.
    $table->text('description');
    $table->json('metadata')->nullable();
    $table->string('ip_address')->nullable();
    $table->text('user_agent')->nullable();
    $table->timestamps();
    
    $table->index(['user_id', 'created_at']);
    $table->index('activity_type');
});
```

#### Model Implementation

```php
// app/Models/UserActivityLog.php
class UserActivityLog extends Model
{
    protected $fillable = [
        'user_id',
        'activity_type',
        'description',
        'metadata',
        'ip_address',
        'user_agent',
    ];

    protected $casts = [
        'metadata' => 'array',
    ];

    public function user()
    {
        return $this->belongsTo(User::class);
    }
}
```

#### Controller Implementation

```php
// In UserController.php
public function activity(Request $request, $id)
{
    // Verify user can view this activity (own or admin)
    $requestingUser = $request->user();
    if ($requestingUser->id != $id && !$requestingUser->hasRole('admin')) {
        return $this->errorResponse('Unauthorized', 403);
    }

    $query = UserActivityLog::where('user_id', $id)
        ->orderBy('created_at', 'desc');

    // Filter by activity type
    if ($request->has('type')) {
        $query->where('activity_type', $request->type);
    }

    $perPage = $request->input('limit', 20);
    $activities = $query->paginate($perPage);

    return $this->paginatedResponse(
        $activities,
        'User activity retrieved successfully'
    );
}
```

**Files to Create:**
- `api/database/migrations/YYYY_MM_DD_create_user_activity_logs_table.php`
- `api/app/Models/UserActivityLog.php`
- `api/app/Http/Traits/LogsActivity.php` (optional trait)

**Files to Modify:**
- `api/app/Http/Controllers/UserController.php` - Add activity method
- `api/routes/api.php` - Add route
- `api/app/Models/User.php` - Add relationship (optional)

**Route:**
```php
Route::get('/users/{id}/activity', [UserController::class, 'activity']);
```

**Testing Requirements:**
- [ ] Returns user's activity log
- [ ] Pagination works correctly
- [ ] Filter by activity type works
- [ ] Authorization check works (own or admin)
- [ ] Unauthorized access returns 403

**Estimated Time:** 4-6 hours

---

## 3. Avatar Upload Endpoint

### 3.1 POST `/users/{id}/upload-avatar`

**Status:** May be redundant  
**Priority:** 🟢 Low  
**Estimated Effort:** 1-2 hours

#### Analysis

**Existing Endpoint:**
- `POST /auth/update-profile-picture` already exists
- This endpoint may be redundant

#### Decision Required

**Option 1: Keep as separate endpoint**
- Provides dedicated avatar upload endpoint
- More RESTful approach
- Clear separation of concerns

**Option 2: Use existing endpoint**
- `/auth/update-profile-picture` already handles this
- No additional work needed
- Document that this endpoint covers avatar uploads

#### Recommended: Option 1 (If needed)

If a dedicated endpoint is required, implement as follows:

**Step 1: Add Route**
```php
Route::post('/users/{id}/upload-avatar', [UserController::class, 'uploadAvatar']);
```

**Step 2: Implement Method**
```php
public function uploadAvatar(Request $request, $id)
{
    $request->validate([
        'avatar' => 'required|image|mimes:jpeg,png,jpg,webp|max:5120', // 5MB
    ]);

    $user = User::findOrFail($id);
    
    // Verify authorization
    if ($request->user()->id != $id && !$request->user()->hasRole('admin')) {
        return $this->errorResponse('Unauthorized', 403);
    }

    // Delete old avatar if exists
    if ($user->profile_photo) {
        Storage::disk('public')->delete('avatars/' . basename($user->profile_photo));
    }

    // Store new avatar
    $path = $request->file('avatar')->store('avatars', 'public');
    $user->profile_photo = $path;
    $user->save();

    return $this->successResponse([
        'avatar_url' => $user->profile_photo
    ], 'Avatar uploaded successfully');
}
```

**Files to Modify:**
- `api/app/Http/Controllers/UserController.php` - Add method
- `api/routes/api.php` - Add route (if needed)

**Testing Requirements:**
- [ ] Valid image uploads successfully
- [ ] Invalid file types rejected
- [ ] File size validation works
- [ ] Old avatar deleted when new one uploaded
- [ ] Authorization check works

**Estimated Time:** 1-2 hours (if needed)

**Note:** Verify with frontend team if this endpoint is actually needed or if `/auth/update-profile-picture` is sufficient.

---

## Implementation Timeline

### Day 1: Password Reset (4-6 hours)

**Morning (2-3 hours):**
- [ ] Implement `POST /auth/forgot-password`
- [ ] Configure email service
- [ ] Test forgot password flow

**Afternoon (2-3 hours):**
- [ ] Implement `POST /auth/reset-password`
- [ ] Test reset password flow
- [ ] Test edge cases (expired tokens, invalid tokens)

### Day 2: User Activity & Avatar (5-8 hours)

**Morning (4-6 hours):**
- [ ] Create user_activity_logs migration
- [ ] Create UserActivityLog model
- [ ] Implement `GET /users/{id}/activity`
- [ ] Add activity logging trait (optional)
- [ ] Test activity endpoint

**Afternoon (1-2 hours):**
- [ ] Review avatar upload requirement
- [ ] Implement `POST /users/{id}/upload-avatar` (if needed)
- [ ] Test avatar upload

---

## Testing Checklist

### Password Reset Endpoints

#### Forgot Password
- [ ] Valid email receives reset link
- [ ] Invalid email returns appropriate error
- [ ] Non-existent email doesn't reveal user existence
- [ ] Email contains valid reset link
- [ ] Rate limiting prevents abuse
- [ ] Multiple requests don't create duplicate tokens
- [ ] Token expires after configured time

#### Reset Password
- [ ] Valid token resets password successfully
- [ ] Invalid token returns error
- [ ] Expired token returns error
- [ ] Password validation works (min length, confirmation)
- [ ] Old password tokens invalidated after reset
- [ ] User can login with new password
- [ ] Old password no longer works

### User Activity Endpoint

- [ ] Returns user's activity log
- [ ] Pagination works correctly
- [ ] Filter by activity type works
- [ ] Returns empty array for new users
- [ ] Authorization check works (own activity or admin)
- [ ] Unauthorized access returns 403
- [ ] Activity log entries are created correctly
- [ ] Metadata is stored and retrieved correctly

### Avatar Upload Endpoint (if implemented)

- [ ] Valid image uploads successfully
- [ ] Invalid file types rejected
- [ ] File size validation works (max 5MB)
- [ ] Old avatar deleted when new one uploaded
- [ ] Returns correct avatar URL
- [ ] Authorization check works
- [ ] Unauthorized access returns 403

---

## Code Quality Requirements

### Standards to Follow

1. **Response Format:**
   - Use `ResponseTrait` for consistent responses
   - Follow existing API response structure:
   ```json
   {
     "code": 200,
     "error": false,
     "status": "success",
     "message": "Operation successful",
     "data": { ... }
   }
   ```

2. **Error Handling:**
   - Use appropriate HTTP status codes
   - Return clear error messages
   - Handle edge cases gracefully

3. **Validation:**
   - Use Laravel Form Requests for complex validation
   - Return validation errors in standard format

4. **Security:**
   - Implement rate limiting for password reset
   - Validate file uploads properly
   - Check authorization for user-specific endpoints
   - Sanitize user inputs

5. **Documentation:**
   - Add PHPDoc comments
   - Update API documentation
   - Document request/response formats

---

## Dependencies & Configuration

### Required Packages
- ✅ Laravel Framework (already installed)
- ✅ Laravel Sanctum (already installed)
- ✅ Email service (needs configuration)

### Configuration Needed

#### Email Configuration (`config/mail.php`)
```php
MAIL_MAILER=smtp
MAIL_HOST=smtp.mailtrap.io
MAIL_PORT=2525
MAIL_USERNAME=your_username
MAIL_PASSWORD=your_password
MAIL_ENCRYPTION=tls
MAIL_FROM_ADDRESS=noreply@researchhub.com
MAIL_FROM_NAME="${APP_NAME}"
```

#### Password Reset Configuration (`config/auth.php`)
- Already configured with password reset tokens table
- Token expiry: 60 minutes (default)
- Throttle: 60 seconds (default)

---

## Files Summary

### Files to Create
1. `api/database/migrations/YYYY_MM_DD_create_user_activity_logs_table.php`
2. `api/app/Models/UserActivityLog.php`
3. `api/app/Http/Traits/LogsActivity.php` (optional)

### Files to Modify
1. `api/routes/api.php` - Add 3-4 routes
2. `api/app/Http/Controllers/AuthController.php` - Complete 2 methods
3. `api/app/Http/Controllers/UserController.php` - Add 1-2 methods
4. `api/app/Models/User.php` - Add relationship (optional)
5. `api/config/mail.php` - Email configuration (if not done)

### Files to Review
1. `api/app/Http/Controllers/AuthController.php` - Check existing update-profile-picture method
2. Frontend requirements - Verify if avatar endpoint is needed

---

## Post-Implementation Tasks

### Immediate
- [ ] Test all endpoints thoroughly
- [ ] Update API documentation
- [ ] Update frontend team on new endpoints
- [ ] Deploy to staging environment

### Follow-up
- [ ] Monitor password reset email delivery
- [ ] Set up activity log cleanup job (optional)
- [ ] Review and optimize activity log queries
- [ ] Consider adding activity log to admin dashboard

---

## Risk Assessment

### Low Risk ✅
- **Password Reset:** Standard Laravel functionality, well-tested
- **Avatar Upload:** Simple file upload, similar to existing implementation

### Medium Risk ⚠️
- **User Activity Log:** New feature, needs careful design for performance
- **Email Configuration:** Requires external service setup

### Mitigation Strategies
- Use Laravel's built-in password reset (proven solution)
- Implement proper indexing for activity logs
- Set up email queue for better performance
- Add rate limiting to prevent abuse
- Test email delivery in staging before production

---

## Success Criteria

### Completion Checklist
- [ ] All 4 endpoints implemented and tested
- [ ] Password reset emails sent successfully
- [ ] Password reset flow works end-to-end
- [ ] User activity log retrieves data correctly
- [ ] Avatar upload works (if implemented)
- [ ] All endpoints return consistent response format
- [ ] Authorization checks work correctly
- [ ] Error handling is comprehensive
- [ ] API documentation updated
- [ ] Code reviewed and approved

### Metrics
- ✅ 100% API endpoint coverage (85/85 endpoints)
- ✅ All endpoints tested and working
- ✅ Response times within acceptable limits
- ✅ No critical security vulnerabilities

---

## Next Steps

### Immediate Actions
1. **Review this plan** with development team
2. **Confirm email service** configuration
3. **Verify avatar endpoint requirement** with frontend team
4. **Set up development environment** for testing

### Week 1 Implementation
1. **Day 1:** Implement password reset endpoints
2. **Day 2:** Implement user activity log endpoint
3. **Day 2:** Implement avatar upload (if needed)
4. **Day 2:** Testing and documentation

### After Implementation
1. Update API documentation
2. Notify frontend team of new endpoints
3. Deploy to staging
4. Monitor and optimize

---

## Conclusion

With **4 endpoints remaining** and an estimated **1-2 days** of work, the ARMPO API can achieve **100% completion**. The implementation is straightforward, using Laravel's built-in features and following existing patterns in the codebase.

**Priority Order:**
1. 🔴 Password reset endpoints (critical for user experience)
2. 🟡 User activity log (useful for admin and analytics)
3. 🟢 Avatar upload (may be redundant, verify first)

**Estimated Completion:** 1-2 days  
**Target:** 100% API completion

---

**Document Version:** 1.0  
**Last Updated:** 2024-12-19  
**Prepared By:** Backend Development Team
