/**
 * Conversations Routes
 * Routes for conversation monitoring (admin only) and user chat
 * 
 * Features:
 * - Claim/release conversations for exclusive attendance
 * - Transfer to store/department
 * - Tenant admin view-only mode
 * 
 * @module routes/conversations
 */

const express = require('express');
const router = express.Router();
const ConversationsController = require('../controllers/ConversationsController');
const ChatController = require('../controllers/ChatController');
const ConversationTransferController = require('../controllers/ConversationTransferController');

// Note: requireAuth and tenantMiddleware are already applied in server.js
// No need to apply them again here

/**
 * @swagger
 * tags:
 *   name: Messages
 *   description: |
 *     Send, receive, and manage WhatsApp messages
 *     
 *     **Common Use Cases:**
 *     - Customer support conversations
 *     - Order notifications and updates
 *     - Appointment reminders
 *     - Marketing campaigns
 *     - Two-way interactive messaging
 *     - Message editing and deletion
 *     - Media sharing (images, videos, documents)
 */

/**
 * @swagger
 * /api/tenant/conversations:
 *   get:
 *     summary: Get all conversations (filtered by user role and claim status)
 *     tags: [Conversations]
 *     security:
 *       - bearerAuth: []
 *     parameters:
 *       - in: query
 *         name: status
 *         schema:
 *           type: string
 *           enum: [waiting, attended, closed, active, archived]
 *         description: Filter by conversation status
 *       - in: query
 *         name: assigned_user_id
 *         schema:
 *           type: integer
 *         description: Filter by assigned user
 *       - in: query
 *         name: search
 *         schema:
 *           type: string
 *         description: Search by contact name or phone
 *       - in: query
 *         name: limit
 *         schema:
 *           type: integer
 *           default: 50
 *         description: Number of conversations to return
 *       - in: query
 *         name: offset
 *         schema:
 *           type: integer
 *           default: 0
 *         description: Offset for pagination
 *     responses:
 *       200:
 *         description: List of conversations
 *       401:
 *         description: Unauthorized
 *       500:
 *         description: Server error
 */
router.get('/', ConversationsController.getConversations);

/**
 * @swagger
 * /api/tenant/conversations/stats:
 *   get:
 *     summary: Get conversation statistics
 *     tags: [Conversations]
 *     security:
 *       - bearerAuth: []
 *     responses:
 *       200:
 *         description: Conversation statistics
 *       401:
 *         description: Unauthorized
 *       500:
 *         description: Server error
 */
// IMPORTANT: Specific routes must come BEFORE /:id to avoid being captured by it
router.get('/stats', ConversationsController.getStats);

/**
 * @swagger
 * /api/tenant/conversations/visibility-settings:
 *   get:
 *     summary: Get conversation visibility settings
 *     tags: [Conversations]
 *     security:
 *       - bearerAuth: []
 *     responses:
 *       200:
 *         description: Visibility settings
 */
router.get('/visibility-settings', ConversationsController.getVisibilitySettings);

/**
 * @swagger
 * /api/tenant/conversations/visibility-settings:
 *   put:
 *     summary: Update conversation visibility settings
 *     tags: [Conversations]
 *     security:
 *       - bearerAuth: []
 *     requestBody:
 *       required: true
 *       content:
 *         application/json:
 *           schema:
 *             type: object
 *             properties:
 *               stores_can_see_new_conversations:
 *                 type: boolean
 *     responses:
 *       200:
 *         description: Settings updated
 */
router.put('/visibility-settings', ConversationsController.updateVisibilitySettings);

/**
 * @swagger
 * /api/tenant/conversations/transfer-options:
 *   get:
 *     summary: Get transfer options (stores, departments, users)
 *     tags: [Conversations]
 *     security:
 *       - bearerAuth: []
 *     responses:
 *       200:
 *         description: Transfer options
 */
router.get('/transfer-options', ConversationTransferController.getTransferOptions);

/**
 * @swagger
 * /api/tenant/conversations/users:
 *   get:
 *     summary: Get list of users for transfer
 *     tags: [Conversations]
 *     security:
 *       - bearerAuth: []
 *     responses:
 *       200:
 *         description: List of users
 */
router.get('/users', ConversationsController.getUsers);

/**
 * @swagger
 * /api/tenant/conversations/{id}/messages:
 *   get:
 *     summary: Get messages in conversation (tenant admin)
 *     tags: [Conversations]
 *     security:
 *       - bearerAuth: []
 *     parameters:
 *       - in: path
 *         name: id
 *         required: true
 *         schema:
 *           type: integer
 *       - in: query
 *         name: page
 *         schema:
 *           type: integer
 *           default: 1
 *       - in: query
 *         name: limit
 *         schema:
 *           type: integer
 *           default: 50
 *       - in: query
 *         name: source
 *         schema:
 *           type: string
 *           default: whatsapp_cloud
 *     responses:
 *       200:
 *         description: List of messages
 *       404:
 *         description: Conversation not found
 */
router.get('/:id/messages', ConversationsController.getMessages);

/**
 * @swagger
 * /api/tenant/conversations/{id}/messages:
 *   post:
 *     summary: Send message as tenant admin
 *     tags: [Conversations]
 *     security:
 *       - bearerAuth: []
 *     parameters:
 *       - in: path
 *         name: id
 *         required: true
 *         schema:
 *           type: integer
 *     requestBody:
 *       required: true
 *       content:
 *         application/json:
 *           schema:
 *             type: object
 *             properties:
 *               message:
 *                 type: string
 *               media_url:
 *                 type: string
 *               media_type:
 *                 type: string
 *     responses:
 *       200:
 *         description: Message sent successfully
 */
router.post('/:id/messages', ConversationsController.sendMessage);

/**
 * @swagger
 * /api/tenant/conversations/{id}/transfer:
 *   post:
 *     summary: Transfer conversation to store, department, or user (ROBUST VERSION)
 *     tags: [Conversations]
 *     security:
 *       - bearerAuth: []
 *     parameters:
 *       - in: path
 *         name: id
 *         required: true
 *         schema:
 *           type: integer
 *     requestBody:
 *       required: true
 *       content:
 *         application/json:
 *           schema:
 *             type: object
 *             required:
 *               - targetType
 *             properties:
 *               targetType:
 *                 type: string
 *                 enum: [store, department, user]
 *                 description: Type of transfer target
 *               targetId:
 *                 type: integer
 *                 description: ID of target (store_id, department_id, or user_id)
 *               targetName:
 *                 type: string
 *                 description: Name of target (for backward compatibility)
 *               reason:
 *                 type: string
 *                 description: Optional transfer reason/note
 *               source:
 *                 type: string
 *                 enum: [whatsapp_cloud, whatsapp_web]
 *                 default: whatsapp_cloud
 *                 description: Conversation source
 *     responses:
 *       200:
 *         description: Conversation transferred successfully
 *       400:
 *         description: Invalid request (missing target or invalid type)
 *       404:
 *         description: Conversation or target not found
 *       500:
 *         description: Server error
 */
router.post('/:id/transfer', ConversationTransferController.transferConversation);

/**
 * @swagger
 * /api/tenant/conversations/{id}/transfer-history:
 *   get:
 *     summary: Get transfer history for a conversation
 *     tags: [Conversations]
 *     security:
 *       - bearerAuth: []
 *     parameters:
 *       - in: path
 *         name: id
 *         required: true
 *         schema:
 *           type: integer
 *       - in: query
 *         name: source
 *         schema:
 *           type: string
 *           enum: [whatsapp_cloud, whatsapp_web]
 *           default: whatsapp_cloud
 *     responses:
 *       200:
 *         description: Transfer history
 */
router.get('/:id/transfer-history', ConversationTransferController.getTransferHistory);

router.delete('/:id/notes', ConversationsController.clearConversationNotes);

/**
 * @swagger
 * /api/tenant/conversations/{id}:
 *   delete:
 *     summary: Delete conversation (admin only with password confirmation)
 *     tags: [Conversations]
 *     security:
 *       - bearerAuth: []
 *     parameters:
 *       - in: path
 *         name: id
 *         required: true
 *         schema:
 *           type: integer
 *     requestBody:
 *       required: true
 *       content:
 *         application/json:
 *           schema:
 *             type: object
 *             required:
 *               - password
 *             properties:
 *               password:
 *                 type: string
 *                 description: Admin login password for confirmation
 *     responses:
 *       200:
 *         description: Conversation deleted successfully
 *       400:
 *         description: Password is required
 *       401:
 *         description: Invalid password
 *       403:
 *         description: Only admins can delete conversations
 *       404:
 *         description: Conversation not found
 */
router.delete('/:id', ConversationsController.deleteConversation);

/**
 * @swagger
 * /api/tenant/conversations/{id}/claim:
 *   post:
 *     summary: Claim a conversation for exclusive attendance
 *     tags: [Conversations]
 *     security:
 *       - bearerAuth: []
 *     parameters:
 *       - in: path
 *         name: id
 *         required: true
 *         schema:
 *           type: integer
 *     responses:
 *       200:
 *         description: Conversation claimed successfully
 *       403:
 *         description: Cannot claim - already claimed by another user or admin
 *       404:
 *         description: Conversation not found
 */
router.post('/:id/claim', ChatController.claimConversation);

/**
 * @swagger
 * /api/tenant/conversations/{id}/release:
 *   post:
 *     summary: Release a claimed conversation
 *     tags: [Conversations]
 *     security:
 *       - bearerAuth: []
 *     parameters:
 *       - in: path
 *         name: id
 *         required: true
 *         schema:
 *           type: integer
 *     responses:
 *       200:
 *         description: Conversation released successfully
 *       404:
 *         description: Conversation not found or not claimed by this user
 */
router.post('/:id/release', ChatController.releaseConversation);

/**
 * @swagger
 * /api/tenant/conversations/{conversationId}/messages/{messageId}:
 *   put:
 *     summary: Edit a message
 *     tags: [Messages]
 *     security:
 *       - bearerAuth: []
 *     parameters:
 *       - in: path
 *         name: conversationId
 *         required: true
 *         schema:
 *           type: integer
 *       - in: path
 *         name: messageId
 *         required: true
 *         schema:
 *           type: integer
 *     responses:
 *       200:
 *         description: Message edited successfully
 *       403:
 *         description: Cannot edit - not the sender or received message
 *       404:
 *         description: Message not found
 */
router.put('/:conversationId/messages/:messageId', ChatController.editMessage);

/**
 * @swagger
 * /api/tenant/conversations/{conversationId}/messages/{messageId}:
 *   delete:
 *     summary: Delete a message
 *     tags: [Conversations]
 *     security:
 *       - bearerAuth: []
 *     parameters:
 *       - in: path
 *         name: conversationId
 *         required: true
 *         schema:
 *           type: integer
 *       - in: path
 *         name: messageId
 *         required: true
 *         schema:
 *           type: integer
 *       - in: query
 *         name: deleteFor
 *         schema:
 *           type: string
 *           enum: [me, everyone]
 *           default: me
 *         description: Delete for me only or for everyone
 *     responses:
 *       200:
 *         description: Message deleted successfully
 *       403:
 *         description: Cannot delete for everyone - not the sender or received message
 *       404:
 *         description: Message not found
 */
router.delete('/:conversationId/messages/:messageId', ChatController.deleteMessage);

/**
 * @swagger
 * /api/tenant/conversations/{id}/status:
 *   put:
 *     summary: Update conversation status
 *     tags: [Conversations]
 *     security:
 *       - bearerAuth: []
 *     parameters:
 *       - in: path
 *         name: id
 *         required: true
 *         schema:
 *           type: integer
 *     requestBody:
 *       required: true
 *       content:
 *         application/json:
 *           schema:
 *             type: object
 *             properties:
 *               status:
 *                 type: string
 *                 enum: [active, archived, closed]
 *     responses:
 *       200:
 *         description: Status updated
 */
router.put('/:id/status', ChatController.updateStatus);

/**
 * @swagger
 * /api/tenant/conversations/{id}/stage:
 *   put:
 *     summary: Update conversation pipeline stage
 *     tags: [Conversations]
 *     security:
 *       - bearerAuth: []
 *     parameters:
 *       - in: path
 *         name: id
 *         required: true
 *         schema:
 *           type: integer
 *     requestBody:
 *       required: true
 *       content:
 *         application/json:
 *           schema:
 *             type: object
 *             properties:
 *               stage:
 *                 type: string
 *                 description: Pipeline stage ID
 *     responses:
 *       200:
 *         description: Stage updated
 */
router.put('/:id/stage', ConversationsController.updateStage);

/**
 * @swagger
 * /api/tenant/conversations/{id}:
 *   get:
 *     summary: Get conversation details with messages
 *     tags: [Conversations]
 *     security:
 *       - bearerAuth: []
 *     parameters:
 *       - in: path
 *         name: id
 *         required: true
 *         schema:
 *           type: integer
 *         description: Conversation ID
 *     responses:
 *       200:
 *         description: Conversation details with messages
 *       404:
 *         description: Conversation not found
 *       401:
 *         description: Unauthorized
 *       500:
 *         description: Server error
 */
// IMPORTANT: This generic /:id route MUST come AFTER all specific routes like /:id/messages
router.get('/:id', ConversationsController.getConversation);

module.exports = router;
