# Super Admin Backend Implementation Plan

## Overview
This document outlines the implementation plan for Super Admin APIs based on the SOW requirements. The admin system will have `/admin` prefix for all routes and separate controllers/services.

## Current Backend Analysis

### Existing Infrastructure
✅ **Already Implemented:**
- User authentication & authorization system
- Admin role middleware (`adminRoleMiddleware.js`)
- User and Vendor models with complete profile management
- Booking system with status tracking
- Event management with approval system
- Inquiry system with chat functionality
- Notification service (Push & In-app)
- Support ticket system
- Marketplace/Product system
- User activity logging infrastructure

✅ **Database Models Available:**
- `UserModel` (with role: 'Admin', 'Vendor', 'User')
- `VendorProfileModel`
- `UserProfileModel`
- `ServiceModel`
- `BookingModel`
- `EventModel`
- `InquiryModel`
- `NotificationModel`
- `SupportTicketModel`
- `ProductModel`
- `ReviewModel`

## Implementation Structure

### 1. Admin Routes Structure
```
/admin/
├── auth/                 # Admin authentication
├── dashboard/            # Dashboard statistics
├── users/               # User management
├── vendors/             # Vendor management
├── bookings/            # Booking management
├── events/              # Event management
├── inquiries/           # Inquiry management
├── feedback/            # Support tickets management
├── notifications/       # Notification management
└── subscriptions/       # Subscription management (UI only)
```

### 2. New Files to Create

#### Controllers
```
src/controllers/admin/
├── adminAuthController.js
├── adminDashboardController.js
├── adminUserController.js
├── adminVendorController.js
├── adminBookingController.js
├── adminEventController.js
├── adminInquiryController.js
├── adminFeedbackController.js
└── adminNotificationController.js
```

#### Services
```
src/services/admin/
├── adminDashboardService.js
├── adminUserService.js
├── adminVendorService.js
├── adminAnalyticsService.js
└── adminNotificationService.js
```

#### Routes
```
src/routes/admin/
├── index.js
├── adminAuthRoutes.js
├── adminDashboardRoutes.js
├── adminUserRoutes.js
├── adminVendorRoutes.js
├── adminBookingRoutes.js
├── adminEventRoutes.js
├── adminInquiryRoutes.js
├── adminFeedbackRoutes.js
└── adminNotificationRoutes.js
```

#### Models (New/Extended)
```
src/db/models/
├── userActivityLogModel.js     # For tracking user actions
├── adminActionLogModel.js      # For tracking admin actions
└── systemSettingsModel.js      # For admin settings
```

## Detailed API Implementation

### 1. Admin Authentication (`/admin/auth`)

#### POST `/admin/auth/login`
```javascript
// adminAuthController.js
export const adminLogin = async (req, res, next) => {
    try {
        const { email, password } = req.body;
        
        // Validate admin credentials
        const admin = await UserModel.findOne({ 
            email, 
            role: USER_ROLES.ADMIN,
            isDeleted: false 
        }).select('+password');
        
        if (!admin || !await bcrypt.compare(password, admin.password)) {
            return next(CustomError.createError('Invalid admin credentials', 401));
        }
        
        // Generate tokens
        const tokens = generateTokens(admin._id);
        
        // Log admin login
        await AdminActionLogModel.create({
            adminId: admin._id,
            action: 'LOGIN',
            description: 'Admin logged into dashboard'
        });
        
        return res.send(CustomSuccess.createSuccess({
            admin: {
                id: admin._id,
                email: admin.email,
                role: admin.role,
                lastLoginAt: admin.lastLoginAt
            },
            tokens
        }, 'Admin login successful', 200));
    } catch (error) {
        return next(error);
    }
};
```

### 2. Dashboard Statistics (`/admin/dashboard`)

#### GET `/admin/dashboard/overview`
```javascript
// adminDashboardController.js
export const getDashboardOverview = async (req, res, next) => {
    try {
        const overview = await adminDashboardService.getOverviewStats();
        
        return res.send(CustomSuccess.createSuccess(
            overview,
            'Dashboard overview retrieved successfully',
            200
        ));
    } catch (error) {
        return next(error);
    }
};

// adminDashboardService.js
export const getOverviewStats = async () => {
    const today = new Date();
    const lastWeek = new Date(today.getTime() - 7 * 24 * 60 * 60 * 1000);
    const lastMonth = new Date(today.getTime() - 30 * 24 * 60 * 60 * 1000);
    
    const [
        totalUsers,
        totalVendors,
        totalEvents,
        totalBookings,
        totalInquiries,
        newUsersThisWeek,
        newVendorsThisWeek,
        recentActivity
    ] = await Promise.all([
        UserModel.countDocuments({ role: 'User', isDeleted: false }),
        UserModel.countDocuments({ role: 'Vendor', isDeleted: false }),
        EventModel.countDocuments({ isActive: true }),
        BookingModel.countDocuments({}),
        InquiryModel.countDocuments({ isActive: true }),
        UserModel.countDocuments({ 
            role: 'User', 
            isDeleted: false,
            createdAt: { $gte: lastWeek }
        }),
        UserModel.countDocuments({ 
            role: 'Vendor', 
            isDeleted: false,
            createdAt: { $gte: lastWeek }
        }),
        getRecentActivity()
    ]);
    
    return {
        statistics: {
            totalUsers,
            totalVendors,
            totalEvents,
            totalBookings,
            totalInquiries,
            newUsersThisWeek,
            newVendorsThisWeek
        },
        recentActivity,
        quickAccess: {
            pendingEvents: await EventModel.countDocuments({ status: 'pending' }),
            activeInquiries: await InquiryModel.countDocuments({ status: 'active' }),
            supportTickets: await SupportTicketModel.countDocuments({ status: 'open' })
        }
    };
};
```

### 3. User Management (`/admin/users`)

#### GET `/admin/users`
```javascript
// adminUserController.js
export const getAllUsers = async (req, res, next) => {
    try {
        const {
            page = 1,
            limit = 10,
            search = '',
            status = '',
            sortBy = 'createdAt',
            sortOrder = 'desc'
        } = req.query;
        
        const result = await adminUserService.getAllUsers({
            page: parseInt(page),
            limit: parseInt(limit),
            search,
            status,
            sortBy,
            sortOrder
        });
        
        return res.send(CustomSuccess.createSuccess(
            result,
            'Users retrieved successfully',
            200
        ));
    } catch (error) {
        return next(error);
    }
};

// PUT `/admin/users/:userId/status`
export const updateUserStatus = async (req, res, next) => {
    try {
        const { userId } = req.params;
        const { action, reason } = req.body; // action: 'block' | 'unblock'
        
        const user = await UserModel.findById(userId);
        if (!user) {
            return next(CustomError.createError('User not found', 404));
        }
        
        // Update user status
        const updatedUser = await UserModel.findByIdAndUpdate(
            userId,
            { 
                isDeleted: action === 'block',
                ...(action === 'block' && { lastBlockedAt: new Date(), blockReason: reason })
            },
            { new: true }
        );
        
        // Log admin action
        await AdminActionLogModel.create({
            adminId: req.user._id,
            action: action.toUpperCase(),
            targetType: 'USER',
            targetId: userId,
            description: `${action === 'block' ? 'Blocked' : 'Unblocked'} user: ${user.email}`,
            metadata: { reason }
        });
        
        // Send notification to user
        if (action === 'block') {
            await NotificationService.sendNotificationToUser(
                userId,
                'ACCOUNT_BLOCKED',
                { reason }
            );
        }
        
        return res.send(CustomSuccess.createSuccess(
            { user: updatedUser },
            `User ${action}ed successfully`,
            200
        ));
    } catch (error) {
        return next(error);
    }
};
```

### 4. Vendor Management (`/admin/vendors`)

#### GET `/admin/vendors`
```javascript
// adminVendorController.js
export const getAllVendors = async (req, res, next) => {
    try {
        const {
            page = 1,
            limit = 10,
            search = '',
            status = '',
            category = '',
            approvalStatus = ''
        } = req.query;
        
        const result = await adminVendorService.getAllVendors({
            page: parseInt(page),
            limit: parseInt(limit),
            search,
            status,
            category,
            approvalStatus
        });
        
        return res.send(CustomSuccess.createSuccess(
            result,
            'Vendors retrieved successfully',
            200
        ));
    } catch (error) {
        return next(error);
    }
};

// PUT `/admin/vendors/:vendorId/approval`
export const updateVendorApproval = async (req, res, next) => {
    try {
        const { vendorId } = req.params;
        const { action, reason } = req.body; // action: 'approve' | 'reject'
        
        const vendor = await UserModel.findById(vendorId);
        if (!vendor || vendor.role !== 'Vendor') {
            return next(CustomError.createError('Vendor not found', 404));
        }
        
        // Update vendor approval status
        const updatedVendor = await UserModel.findByIdAndUpdate(
            vendorId,
            {
                isVerified: action === 'approve',
                ...(action === 'reject' && { rejectionReason: reason }),
                approvedBy: req.user._id,
                approvedAt: new Date()
            },
            { new: true }
        );
        
        // Log admin action
        await AdminActionLogModel.create({
            adminId: req.user._id,
            action: `VENDOR_${action.toUpperCase()}`,
            targetType: 'VENDOR',
            targetId: vendorId,
            description: `${action === 'approve' ? 'Approved' : 'Rejected'} vendor: ${vendor.email}`,
            metadata: { reason }
        });
        
        // Send notification to vendor
        await NotificationService.sendNotificationToUser(
            vendorId,
            action === 'approve' ? 'VENDOR_APPROVED' : 'VENDOR_REJECTED',
            { reason }
        );
        
        return res.send(CustomSuccess.createSuccess(
            { vendor: updatedVendor },
            `Vendor ${action}d successfully`,
            200
        ));
    } catch (error) {
        return next(error);
    }
};
```

### 5. Event Management (`/admin/events`)
**Note: Events already have admin functionality in `adminEventController.js`**

#### Additional Features Needed:
```javascript
// adminEventController.js (extend existing)

// GET `/admin/events/analytics`
export const getEventAnalytics = async (req, res, next) => {
    try {
        const analytics = await adminEventService.getEventAnalytics();
        
        return res.send(CustomSuccess.createSuccess(
            analytics,
            'Event analytics retrieved successfully',
            200
        ));
    } catch (error) {
        return next(error);
    }
};

// PUT `/admin/events/:eventId/track-click`
export const trackEventClick = async (req, res, next) => {
    try {
        const { eventId } = req.params;
        const { url, type } = req.body; // type: 'URL' | 'PHONE'
        
        // Track event click/contact
        await EventInteractionModel.create({
            eventId,
            interactionType: type,
            clickedUrl: url,
            clickedAt: new Date(),
            adminId: req.user._id
        });
        
        return res.send(CustomSuccess.createSuccess(
            { tracked: true },
            'Event interaction tracked',
            200
        ));
    } catch (error) {
        return next(error);
    }
};
```

### 6. Booking Management (`/admin/bookings`)

#### GET `/admin/bookings`
```javascript
// adminBookingController.js
export const getAllBookings = async (req, res, next) => {
    try {
        const {
            page = 1,
            limit = 10,
            status = '',
            dateFrom = '',
            dateTo = '',
            search = ''
        } = req.query;
        
        const filters = {};
        
        if (status) filters.status = status;
        if (search) {
            filters.$or = [
                { 'user.email': { $regex: search, $options: 'i' } },
                { 'vendor.email': { $regex: search, $options: 'i' } },
                { 'service.serviceName': { $regex: search, $options: 'i' } }
            ];
        }
        if (dateFrom || dateTo) {
            filters.bookingDate = {};
            if (dateFrom) filters.bookingDate.$gte = new Date(dateFrom);
            if (dateTo) filters.bookingDate.$lte = new Date(dateTo);
        }
        
        const skip = (page - 1) * limit;
        
        const [bookings, total] = await Promise.all([
            BookingModel.aggregate([
                {
                    $lookup: {
                        from: 'users',
                        localField: 'userId',
                        foreignField: '_id',
                        as: 'user',
                        pipeline: [{ $project: { email: 1, isDeleted: 1 } }]
                    }
                },
                {
                    $lookup: {
                        from: 'users',
                        localField: 'vendorId',
                        foreignField: '_id',
                        as: 'vendor',
                        pipeline: [{ $project: { email: 1, isDeleted: 1 } }]
                    }
                },
                {
                    $lookup: {
                        from: 'services',
                        localField: 'serviceId',
                        foreignField: '_id',
                        as: 'service',
                        pipeline: [{ $project: { serviceName: 1, typeOfActivity: 1 } }]
                    }
                },
                { $unwind: '$user' },
                { $unwind: '$vendor' },
                { $unwind: '$service' },
                { $match: filters },
                { $sort: { createdAt: -1 } },
                { $skip: skip },
                { $limit: parseInt(limit) }
            ]),
            BookingModel.aggregate([
                // Same lookups and match as above
                { $count: 'total' }
            ])
        ]);
        
        return res.send(CustomSuccess.createSuccess({
            bookings,
            pagination: {
                currentPage: parseInt(page),
                totalPages: Math.ceil(total[0]?.total / limit || 0),
                totalBookings: total[0]?.total || 0,
                hasNextPage: page < Math.ceil(total[0]?.total / limit || 0),
                hasPrevPage: page > 1
            }
        }, 'Bookings retrieved successfully', 200));
    } catch (error) {
        return next(error);
    }
};
```

### 7. Inquiry Management (`/admin/inquiries`)
**Note: Already partially implemented in `inquiryController.js`**

#### Extend existing functionality:
```javascript
// adminInquiryController.js (extend existing)

// GET `/admin/inquiries/analytics`
export const getInquiryAnalytics = async (req, res, next) => {
    try {
        const analytics = await adminInquiryService.getInquiryAnalytics();
        
        return res.send(CustomSuccess.createSuccess(
            analytics,
            'Inquiry analytics retrieved successfully',
            200
        ));
    } catch (error) {
        return next(error);
    }
};
```

### 8. Feedback/Support Management (`/admin/feedback`)

#### GET `/admin/feedback/tickets`
```javascript
// adminFeedbackController.js
export const getAllSupportTickets = async (req, res, next) => {
    try {
        const {
            page = 1,
            limit = 10,
            status = '',
            priority = '',
            category = '',
            search = ''
        } = req.query;
        
        const result = await adminSupportService.getAllTickets({
            page: parseInt(page),
            limit: parseInt(limit),
            status,
            priority,
            category,
            search
        });
        
        return res.send(CustomSuccess.createSuccess(
            result,
            'Support tickets retrieved successfully',
            200
        ));
    } catch (error) {
        return next(error);
    }
};

// PUT `/admin/feedback/tickets/:ticketId/resolve`
export const resolveTicket = async (req, res, next) => {
    try {
        const { ticketId } = req.params;
        const { resolution, internalNotes } = req.body;
        
        const ticket = await SupportTicketModel.findByIdAndUpdate(
            ticketId,
            {
                status: 'resolved',
                resolution,
                resolvedBy: req.user._id,
                resolvedAt: new Date(),
                internalNotes
            },
            { new: true }
        ).populate('user', 'email');
        
        if (!ticket) {
            return next(CustomError.createError('Support ticket not found', 404));
        }
        
        // Log admin action
        await AdminActionLogModel.create({
            adminId: req.user._id,
            action: 'TICKET_RESOLVED',
            targetType: 'SUPPORT_TICKET',
            targetId: ticketId,
            description: `Resolved support ticket for user: ${ticket.user.email}`
        });
        
        // Notify user
        await NotificationService.notifySupportTicketReplied(ticket.user._id);
        
        return res.send(CustomSuccess.createSuccess(
            { ticket },
            'Support ticket resolved successfully',
            200
        ));
    } catch (error) {
        return next(error);
    }
};
```

### 9. Notification Management (`/admin/notifications`)

#### POST `/admin/notifications/send`
```javascript
// adminNotificationController.js
export const sendNotifications = async (req, res, next) => {
    try {
        const { 
            recipients, // 'all' | 'users' | 'vendors' | array of userIds
            title,
            body,
            type = 'ADMIN_ANNOUNCEMENT',
            payload = {}
        } = req.body;
        
        let targetUsers = [];
        
        if (recipients === 'all') {
            targetUsers = await UserModel.find({ 
                isDeleted: false,
                role: { $in: ['User', 'Vendor'] }
            }).select('_id');
        } else if (recipients === 'users') {
            targetUsers = await UserModel.find({ 
                isDeleted: false,
                role: 'User'
            }).select('_id');
        } else if (recipients === 'vendors') {
            targetUsers = await UserModel.find({ 
                isDeleted: false,
                role: 'Vendor'
            }).select('_id');
        } else if (Array.isArray(recipients)) {
            targetUsers = await UserModel.find({
                _id: { $in: recipients },
                isDeleted: false
            }).select('_id');
        }
        
        // Send notifications to all target users
        const notificationPromises = targetUsers.map(user =>
            NotificationService.sendNotificationToUser(user._id, type, {
                ...payload,
                customTitle: title,
                customBody: body,
                adminSent: true,
                adminId: req.user._id
            })
        );
        
        const results = await Promise.allSettled(notificationPromises);
        const successful = results.filter(r => r.status === 'fulfilled').length;
        
        // Log admin action
        await AdminActionLogModel.create({
            adminId: req.user._id,
            action: 'BULK_NOTIFICATION_SENT',
            description: `Sent notifications to ${successful} users`,
            metadata: { 
                recipientType: recipients,
                title,
                totalTargets: targetUsers.length,
                successful
            }
        });
        
        return res.send(CustomSuccess.createSuccess({
            totalTargets: targetUsers.length,
            successful,
            failed: targetUsers.length - successful
        }, 'Notifications sent successfully', 200));
    } catch (error) {
        return next(error);
    }
};
```

### 10. Subscription Management (`/admin/subscriptions`)
**Note: UI only with mock APIs**

```javascript
// adminSubscriptionController.js
export const getAllSubscriptions = async (req, res, next) => {
    try {
        // Mock data for now
        const mockSubscriptions = [
            {
                id: '1',
                vendorId: 'vendor1',
                vendorEmail: 'vendor1@example.com',
                plan: 'Premium',
                status: 'active',
                startDate: '2024-01-01',
                endDate: '2024-12-31',
                amount: 99.99,
                features: ['Unlimited Services', 'Priority Support', 'Analytics']
            }
        ];
        
        return res.send(CustomSuccess.createSuccess({
            subscriptions: mockSubscriptions,
            pagination: {
                currentPage: 1,
                totalPages: 1,
                totalSubscriptions: mockSubscriptions.length
            }
        }, 'Subscriptions retrieved successfully (Mock Data)', 200));
    } catch (error) {
        return next(error);
    }
};

export const updateSubscription = async (req, res, next) => {
    try {
        const { subscriptionId } = req.params;
        const { action } = req.body; // 'upgrade', 'downgrade', 'cancel'
        
        // Mock response
        return res.send(CustomSuccess.createSuccess({
            message: `Subscription ${action} operation completed (Mock)`
        }, `Subscription ${action}d successfully`, 200));
    } catch (error) {
        return next(error);
    }
};
```

## Additional Models Needed

### 1. User Activity Log Model
```javascript
// src/db/models/userActivityLogModel.js
import mongoose, { Schema } from "mongoose";

const UserActivityLogSchema = new Schema({
    userId: {
        type: Schema.Types.ObjectId,
        ref: 'user',
        required: true,
        index: true
    },
    action: {
        type: String,
        required: true,
        enum: [
            'LOGIN', 'LOGOUT', 'PROFILE_UPDATE', 'SERVICE_BOOK',
            'SERVICE_CANCEL', 'EVENT_CREATE', 'EVENT_JOIN',
            'INQUIRY_CREATE', 'PRODUCT_CREATE', 'REVIEW_ADD'
        ]
    },
    description: String,
    ipAddress: String,
    userAgent: String,
    metadata: Schema.Types.Mixed
}, {
    timestamps: true
});

export default mongoose.model('userActivityLog', UserActivityLogSchema);
```

### 2. Admin Action Log Model
```javascript
// src/db/models/adminActionLogModel.js
import mongoose, { Schema } from "mongoose";

const AdminActionLogSchema = new Schema({
    adminId: {
        type: Schema.Types.ObjectId,
        ref: 'user',
        required: true,
        index: true
    },
    action: {
        type: String,
        required: true
    },
    targetType: {
        type: String,
        enum: ['USER', 'VENDOR', 'EVENT', 'BOOKING', 'INQUIRY', 'SUPPORT_TICKET']
    },
    targetId: {
        type: Schema.Types.ObjectId
    },
    description: {
        type: String,
        required: true
    },
    metadata: Schema.Types.Mixed
}, {
    timestamps: true
});

export default mongoose.model('adminActionLog', AdminActionLogSchema);
```

## Main Admin Routes Index

```javascript
// src/routes/admin/index.js
import { Router } from 'express';
import { authMiddleware } from '../../middlrewares/authMiddleware.js';
import { adminRoleMiddleware } from '../../middlrewares/adminRoleMiddleware.js';

// Import all admin route modules
import adminAuthRoutes from './adminAuthRoutes.js';
import adminDashboardRoutes from './adminDashboardRoutes.js';
import adminUserRoutes from './adminUserRoutes.js';
import adminVendorRoutes from './adminVendorRoutes.js';
import adminBookingRoutes from './adminBookingRoutes.js';
import adminEventRoutes from './adminEventRoutes.js';
import adminInquiryRoutes from './adminInquiryRoutes.js';
import adminFeedbackRoutes from './adminFeedbackRoutes.js';
import adminNotificationRoutes from './adminNotificationRoutes.js';

export const AdminRoutes = Router();

// Public admin routes (no auth required)
AdminRoutes.use('/auth', adminAuthRoutes);

// Protected admin routes (auth + admin role required)
AdminRoutes.use(authMiddleware);
AdminRoutes.use(adminRoleMiddleware);

AdminRoutes.use('/dashboard', adminDashboardRoutes);
AdminRoutes.use('/users', adminUserRoutes);
AdminRoutes.use('/vendors', adminVendorRoutes);
AdminRoutes.use('/bookings', adminBookingRoutes);
AdminRoutes.use('/events', adminEventRoutes);
AdminRoutes.use('/inquiries', adminInquiryRoutes);
AdminRoutes.use('/feedback', adminFeedbackRoutes);
AdminRoutes.use('/notifications', adminNotificationRoutes);
// Note: Subscriptions will be handled by frontend mock APIs only
```

## Integration with Main App

```javascript
// src/app.js (update existing)
import { AdminRoutes } from './routes/admin/index.js';

// Add admin routes
app.use('/admin', AdminRoutes);
```

## Key Features Summary

### ✅ Dashboard Login & Statistics
- Admin authentication with separate login endpoint
- Overview statistics (users, vendors, events, bookings)
- Recent activity feed
- Quick access to pending items

### ✅ User Management
- List all users with search, filter, pagination
- View/edit user profiles
- Block/unblock user accounts
- User activity logs and behavior tracking
- Group users by criteria

### ✅ Vendor Management
- List all vendors with categories
- Approve/reject vendor accounts
- Monitor vendor reviews and ratings
- Enable/disable vendor accounts

### ✅ Booking Management
- Monitor all user bookings
- Review and track canceled bookings
- Booking analytics and reporting

### ✅ Event Management
- View, add, edit, delete events
- Approve events posted by users/vendors
- Event attendance and review data
- Track event reporting via URL/Contact clicks

### ✅ Inquiry Management
- Manage user inquiries
- Monitor inquiry responses
- Inquiry analytics

### ✅ Support Management
- Address user/vendor feedback
- Support ticket resolution system
- Issue tracking

### ✅ Notification System
- Send targeted notifications to users/vendors
- Push notifications for discounts, subscriptions
- Notification management dashboard

### ✅ Subscription Management (Mock UI)
- Monitor vendor subscriptions and payments
- Manage subscription plans
- Billing and revenue tracking (UI only)

### ✅ Vendor Approval Workflow
- All vendor accounts require admin approval
- Comprehensive approval process to prevent illegal products

## Next Steps

1. **Create all controller files** with the implementations above
2. **Create service files** for business logic
3. **Create route files** for API endpoints
4. **Create additional models** for logging and analytics
5. **Test all endpoints** with proper error handling
6. **Add comprehensive logging** for admin actions
7. **Implement rate limiting** for admin APIs
8. **Add API documentation** with Swagger/OpenAPI

This implementation leverages your existing robust backend infrastructure while adding comprehensive admin functionality as per the SOW requirements.
