const express = require('express');
const router = express.Router();
const supportController = require('../controllers/support.controller.js');
const { isAuthenticated, allowRoles } = require('../middlewares/authenticate.js');
const { upload } = require('../middlewares/multer.middleware');
const { checkPermission } = require('../middlewares/checkPermission.js');

// All routes require authentication
router.use(isAuthenticated);

// ==========================================
// SUPPORT INFO ROUTES (Common)
// ==========================================

router.get('/categories',
    /* #swagger.tags = ['Support']
       #swagger.summary = 'Get support ticket categories'
       #swagger.description = 'Retrieves a list of ticket categories based on the logged-in user\'s role.'
       #swagger.responses[200] = {
           description: 'List of categories retrieved successfully',
           schema: { success: true, data: ['Booking Issue', 'Payment Issue', 'Profile Issue'] }
       }
    */
    supportController.getCategories
);

router.get('/callback-reasons',
    /* #swagger.tags = ['Support']
       #swagger.summary = 'Get callback reason categories'
       #swagger.description = 'Retrieves a list of predefined reasons for requesting a callback.'
       #swagger.responses[200] = {
           description: 'List of callback reasons retrieved successfully',
           schema: { success: true, data: ['Wait Time', 'Driver Behavior', 'Technical Issue'] }
       }
    */
    supportController.getCallbackReasons
);

router.get('/time-slots',
    /* #swagger.tags = ['Support']
       #swagger.summary = 'Get available callback time slots'
       #swagger.description = 'Retrieves a list of available time slots for scheduling a callback.'
       #swagger.responses[200] = {
           description: 'List of time slots retrieved successfully',
           schema: { success: true, data: ['09:00 AM - 12:00 PM', '12:00 PM - 03:00 PM', '03:00 PM - 06:00 PM'] }
       }
    */
    supportController.getTimeSlots
);

router.get('/stats',
    /* #swagger.tags = ['Support']
       #swagger.summary = 'Get support statistics'
       #swagger.description = 'Retrieves support-related statistics (total, open, closed tickets) for the logged-in user.'
       #swagger.responses[200] = {
           description: 'Statistics retrieved successfully',
           schema: { success: true, data: { totalTickets: 10, openTickets: 2, completedTickets: 8 } }
       }
    */
    supportController.getSupportStats
);

router.get('/orders',
    /* #swagger.tags = ['Support']
       #swagger.summary = 'Get my recent orders'
       #swagger.description = 'Retrieves a list of recent orders for the logged-in user to associate with a ticket.'
       #swagger.responses[200] = {
           description: 'Orders retrieved successfully',
           schema: { success: true, data: [{ _id: 'order123', orderId: 'ORD-1001', createdAt: '2023-10-27T10:00:00Z' }] }
       }
    */
    allowRoles('user'), supportController.getMyOrders
);

// ==========================================
// TICKET ROUTES
// ==========================================

router.post('/',
    upload.array('attachments', 5),
    /* #swagger.tags = ['Support']
       #swagger.summary = 'Create a new support ticket'
       #swagger.description = 'Creates a new support ticket with optional attachments.'
       #swagger.consumes = ['multipart/form-data']
       #swagger.parameters['attachments'] = {
           in: 'formData',
           type: 'file',
           description: 'Up to 5 file attachments'
       }
       #swagger.parameters['category'] = {
           in: 'formData',
           type: 'string',
           required: true,
           description: 'Ticket category'
       }
       #swagger.parameters['subject'] = {
           in: 'formData',
           type: 'string',
           description: 'Ticket subject'
       }
       #swagger.parameters['text'] = {
           in: 'formData',
           type: 'string',
           required: true,
           description: 'Message content'
       }
       #swagger.parameters['orderId'] = {
           in: 'formData',
           type: 'string',
           description: 'Optional order ID associated with the ticket'
       }
       #swagger.responses[201] = {
           description: 'Ticket created successfully',
           schema: { success: true, message: 'Ticket created successfully', data: { _id: 'ticket123', status: 'open' } }
       }
    */
    supportController.createTicket
);

router.get('/my',
    /* #swagger.tags = ['Support']
       #swagger.summary = 'Get my support tickets'
       #swagger.description = 'Retrieves a paginated list of support tickets for the logged-in user.'
       #swagger.parameters['page'] = { in: 'query', type: 'integer' }
       #swagger.parameters['limit'] = { in: 'query', type: 'integer' }
       #swagger.parameters['status'] = { in: 'query', type: 'string' }
       #swagger.responses[200] = {
           description: 'Tickets retrieved successfully',
           schema: { success: true, count: 1, data: [{ _id: 'ticket123', subject: '...', status: 'open' }] }
       }
    */
    supportController.getMyTickets
);

// Legacy/Specific routes if still needed by frontend
router.get('/vendor',
    /* #swagger.tags = ['Support']
       #swagger.summary = 'Get vendor tickets'
       #swagger.description = 'Alternative route for vendors to get their tickets.'
       #swagger.responses[200] = {
           description: 'Tickets retrieved successfully'
       }
    */
    allowRoles('vendor'), supportController.getMyTickets // getMyTickets is role-aware
);

// ==========================================
// CALLBACK REQUEST ROUTES
// ==========================================

router.post('/callback',
    /* #swagger.tags = ['Support']
       #swagger.summary = 'Request a callback'
       #swagger.description = 'Creates a request for a support agent to call back the user.'
       #swagger.parameters['body'] = {
           in: 'body',
           description: 'Callback request details',
           schema: { name: 'John Doe', contact: '1234567890', reasonCategory: 'Payment Issue', preferredSlot:{ date: '2024-01-01', timeSlot: '10:00 AM - 12:00 PM' } }
       }
       #swagger.responses[201] = {
           description: 'Callback request submitted successfully',
           schema: { success: true, message: 'Callback request submitted successfully', data: { _id: 'callback123' } }
       }
    */
    supportController.requestCallback
);

router.get('/callback',
    /* #swagger.tags = ['Support']
       #swagger.summary = 'Get my callback requests'
       #swagger.description = 'Retrieves a list of callback requests for the logged-in user.'
       #swagger.parameters['page'] = { in: 'query', type: 'integer' }
       #swagger.parameters['limit'] = { in: 'query', type: 'integer' }
       #swagger.responses[200] = {
           description: 'Callback requests retrieved successfully',
           schema: { success: true, data: [{ _id: 'callback123', status: 'pending' }] }
       }
    */
    supportController.getMyCallbackRequests
);

router.delete('/callback/:id',
    /* #swagger.tags = ['Support']
       #swagger.summary = 'Cancel callback request'
       #swagger.description = 'Cancels a pending callback request.'
       #swagger.parameters['id'] = { description: 'Callback request ID' }
       #swagger.responses[200] = {
           description: 'Callback request cancelled successfully',
           schema: { success: true, message: 'Callback request cancelled successfully' }
       }
    */
    supportController.cancelCallback
);

// ==========================================
// ADMIN SUPPORT MANAGEMENT (Admins only)
// ==========================================

router.get('/admin/dashboard',
    /* #swagger.tags = ['Support : Management']
       #swagger.summary = 'Get support management dashboard'
       #swagger.description = 'Retrieves dashboard statistics for support management.'
       #swagger.responses[200] = {
           description: 'Dashboard data retrieved successfully'
       }
    */
    allowRoles('super-admin', 'zone-admin', 'vendor', 'staff'), checkPermission("manage_support"), supportController.getManagementDashboard
);

router.get('/admin/analytics',
    /* #swagger.tags = ['Support : Management']
       #swagger.summary = 'Get support analytics'
       #swagger.description = 'Retrieves support-related analytics and metrics.'
       #swagger.parameters['period'] = { in: 'query', type: 'string', enum: ['daily', 'weekly', 'monthly'] }
       #swagger.responses[200] = {
           description: 'Analytics retrieved successfully'
       }
    */
    allowRoles('super-admin', 'zone-admin', 'vendor', 'staff'), checkPermission("manage_support"), supportController.getAnalytics
);

router.get('/all',
    /* #swagger.tags = ['Support : Management']
       #swagger.summary = 'Get all tickets (Management)'
       #swagger.description = 'Retrieves a list of all tickets across the system with advanced filtering for Admins and Vendors.'
       #swagger.parameters['page'] = { in: 'query', type: 'integer' }
       #swagger.parameters['status'] = { in: 'query', type: 'string', enum: ['open', 'pending', 'closed'] }
       #swagger.parameters['category'] = { in: 'query', type: 'string' }
       #swagger.parameters['zone'] = { in: 'query', type: 'string' }
       #swagger.parameters['vendor'] = { in: 'query', type: 'string' }
       #swagger.parameters['search'] = { in: 'query', type: 'string' }
       #swagger.parameters['dateRange'] = { in: 'query', type: 'string', description: 'YYYY-MM-DD,YYYY-MM-DD' }
       #swagger.parameters['creatorType'] = { in: 'query', type: 'string', enum: ['user', 'driver', 'vendor', 'zone-admin', 'super-admin', 'all'] }
       #swagger.parameters['escalated'] = { in: 'query', type: 'boolean' }
       #swagger.parameters['priority'] = { in: 'query', type: 'string', enum: ['low', 'normal', 'high', 'urgent', 'all'] }
       #swagger.responses[200] = {
           description: 'Tickets retrieved successfully',
           schema: { success: true, tickets: [], pagination: {} }
       }
    */
    allowRoles('super-admin', 'zone-admin', 'vendor', 'staff'), checkPermission("manage_support"), supportController.getManagementTickets
);

router.get('/callback/all',
    /* #swagger.tags = ['Support : Management']
       #swagger.summary = 'Get all callback requests (Management)'
       #swagger.description = 'Retrieves a list of all callback requests across the system.'
       #swagger.responses[200] = {
           description: 'Requests retrieved successfully'
       }
    */
    allowRoles('super-admin', 'zone-admin', 'vendor', 'staff'), checkPermission("manage_support"), supportController.getManagementCallbackRequests
);

// Compensation Management
router.get('/compensation',
    /* #swagger.tags = ['Support : Compensation']
       #swagger.summary = 'Get all compensations'
       #swagger.description = 'Retrieves a list of proposed, approved, and processed compensations. Access restricted by role (Vendor/Zone Admin see related, Super Admin sees all).'
       #swagger.parameters['status'] = { in: 'query', type: 'string', enum: ['proposed', 'approved', 'processed', 'rejected'] }
       #swagger.parameters['page'] = { in: 'query', type: 'integer' }
       #swagger.responses[200] = {
           description: 'Compensations retrieved successfully',
           schema: { success: true, compensations: [], pagination: {} }
       }
    */
    allowRoles('super-admin', 'zone-admin', 'vendor', 'staff'), checkPermission("manage_support"), supportController.getCompensations
);

router.post('/admin/compensation/propose',
    /* #swagger.tags = ['Support : Compensation']
       #swagger.summary = 'Propose compensation'
       #swagger.description = 'Proposes a new compensation for a specific ticket. The "customer" is automatically determined from the ticket.'
       #swagger.parameters['body'] = {
           in: 'body',
           required: true,
           schema: { ticketId: '658af...', amount: 100, reason: 'Long wait time' }
       }
       #swagger.responses[201] = {
           description: 'Compensation proposed successfully',
           schema: { success: true, data: { _id: '...', status: 'proposed' } }
       }
       #swagger.responses[400] = {
           description: 'Bad Request (e.g., compensation already exists)'
       }
    */
    allowRoles('super-admin', 'zone-admin', 'staff'), checkPermission("manage_financials"), supportController.proposeCompensation
);

router.patch('/admin/compensation/:id/approve',
    /* #swagger.tags = ['Support : Compensation']
       #swagger.summary = 'Approve compensation'
       #swagger.description = 'Approves a proposed compensation. Restricted to Super Admin.'
       #swagger.parameters['id'] = { description: 'Compensation ID' }
       #swagger.responses[200] = {
           description: 'Compensation approved successfully',
           schema: { success: true, data: { status: 'approved' } }
       }
    */
    allowRoles('super-admin', 'staff'), checkPermission("manage_financials"), supportController.approveCompensation
);

router.patch('/admin/compensation/:id/process',
    /* #swagger.tags = ['Support : Compensation']
       #swagger.summary = 'Process compensation'
       #swagger.description = 'Marks an approved compensation as processed (paid). Restricted to Super Admin.'
       #swagger.parameters['id'] = { description: 'Compensation ID' }
       #swagger.parameters['body'] = {
           in: 'body',
           required: true,
           schema: { paymentMethod: 'wallet', transactionId: 'TXN123', notes: 'Refunded to wallet' }
       }
       #swagger.responses[200] = {
           description: 'Compensation processed successfully',
           schema: { success: true, data: { status: 'processed' } }
       }
    */
    allowRoles('super-admin', 'staff'), checkPermission("manage_financials"), supportController.processCompensation
);

router.patch('/admin/compensation/:id/reject',
    /* #swagger.tags = ['Support : Compensation']
       #swagger.summary = 'Reject compensation'
       #swagger.description = 'Rejects a proposed compensation.'
       #swagger.parameters['id'] = { description: 'Compensation ID' }
       #swagger.parameters['body'] = {
           in: 'body',
           required: true,
           schema: { reason: 'Invalid claim' }
       }
       #swagger.responses[200] = {
           description: 'Compensation rejected successfully'
       }
    */
    allowRoles('super-admin', 'zone-admin', 'staff'), checkPermission("manage_financials"), supportController.rejectCompensation
);

// ==========================================
// TICKET ID ROUTES (Must be last to avoid conflicts)
// ==========================================

router.get('/:id',
    /* #swagger.tags = ['Support']
       #swagger.summary = 'Get ticket details'
       #swagger.description = 'Retrieves detailed information about a specific ticket, including its messages.'
       #swagger.parameters['id'] = { description: 'Ticket ID' }
       #swagger.responses[200] = {
           description: 'Ticket details retrieved successfully',
           schema: { success: true, data: { _id: 'ticket123', messages: [] } }
       }
    */
    supportController.getTicketDetails
);

router.post('/:id/messages',
    upload.array('attachments', 5),
    /* #swagger.tags = ['Support']
       #swagger.summary = 'Add message to ticket'
       #swagger.description = 'Adds a new message to an existing support ticket.'
       #swagger.consumes = ['multipart/form-data']
       #swagger.parameters['id'] = { description: 'Ticket ID' }
       #swagger.parameters['attachments'] = {
           in: 'formData',
           type: 'file',
           description: 'Up to 5 file attachments'
       }
       #swagger.parameters['text'] = {
           in: 'formData',
           type: 'string',
           required: true,
           description: 'Message content'
       }
       #swagger.parameters['isInternal'] = {
           in: 'formData',
           type: 'boolean',
           description: 'Whether it is an internal admin note'
       }
       #swagger.responses[200] = {
           description: 'Message added successfully'
       }
    */
    supportController.addMessage
);

router.post('/:id/escalate',
    /* #swagger.tags = ['Support : Management']
       #swagger.summary = 'Escalate ticket'
       #swagger.description = 'Escalates a ticket to higher priority.'
       #swagger.parameters['id'] = { description: 'Ticket ID' }
       #swagger.parameters['body'] = {
           in: 'body',
           schema: { reason: '...', priority: 'high' }
       }
       #swagger.responses[200] = {
           description: 'Ticket escalated successfully'
       }
    */
    allowRoles('super-admin', 'zone-admin', 'vendor', 'staff'), checkPermission("manage_support"), supportController.escalateTicket
);

router.post('/:id/assign',
    /* #swagger.tags = ['Support : Admin']
       #swagger.summary = 'Assign ticket'
       #swagger.description = 'Assigns a ticket to a specific agent or vendor.'
       #swagger.parameters['id'] = { description: 'Ticket ID' }
       #swagger.parameters['body'] = {
           in: 'body',
           schema: { assignTo: '...', assignType: 'admin' }
       }
       #swagger.responses[200] = {
           description: 'Ticket assigned successfully'
       }
    */
    allowRoles('super-admin', 'zone-admin', 'staff'), checkPermission("manage_support"), supportController.assignTicket
);

router.patch('/:id/status',
    /* #swagger.tags = ['Support']
       #swagger.summary = 'Update ticket status'
       #swagger.description = 'Updates the status of a ticket (e.g., open, closed). restricted to specific roles.'
       #swagger.parameters['id'] = { description: 'Ticket ID' }
       #swagger.parameters['body'] = {
           in: 'body',
           schema: { status: 'closed' }
       }
       #swagger.responses[200] = {
           description: 'Status updated successfully'
       }
    */
    allowRoles('super-admin', 'zone-admin', 'vendor', 'staff'), checkPermission("manage_support"), supportController.updateStatus
);

// Callback Management (Admin)
router.patch('/callback/:id/schedule',
    /* #swagger.tags = ['Support : Admin']
       #swagger.summary = 'Schedule callback'
       #swagger.description = 'Schedules a specific time for the callback.'
       #swagger.parameters['id'] = { description: 'Callback request ID' }
       #swagger.responses[200] = {
           description: 'Callback scheduled successfully'
       }
    */
    allowRoles('super-admin', 'zone-admin', 'staff'), checkPermission("manage_support"), supportController.scheduleCallback
);

router.patch('/callback/:id/complete',
    /* #swagger.tags = ['Support : Admin']
       #swagger.summary = 'Complete callback'
       #swagger.description = 'Marks a callback request as completed.'
       #swagger.parameters['id'] = { description: 'Callback request ID' }
       #swagger.responses[200] = {
           description: 'Callback completed successfully'
       }
    */
    allowRoles('super-admin', 'zone-admin', 'staff'), checkPermission("manage_support"), supportController.completeCallback
);

module.exports = router;

