const express = require('express');
const router = express.Router();
const GroupRepository = require('../repositories/GroupRepository');
const { requireAdminAuth } = require('../middlewares/auth');
const { requireCsrf } = require('../middlewares/csrf');

router.use(requireAdminAuth);
router.use(requireCsrf);

/**
 * @swagger
 * /{groupId}/reorder:
 *   put:
 *     tags: [Admin]
 *     summary: Reorder images within a group
 *     description: Updates the display order of images in a group. All image IDs of the group must be provided in the desired order.
 *     parameters:
 *       - in: path
 *         name: groupId
 *         required: true
 *         schema:
 *           type: string
 *           example: "cTV24Yn-a"
 *         description: Unique identifier of the group
 *     requestBody:
 *       required: true
 *       content:
 *         application/json:
 *           schema:
 *             type: object
 *             required:
 *               - imageIds
 *             properties:
 *               imageIds:
 *                 type: array
 *                 items:
 *                   type: integer
 *                 example: [123, 456, 789]
 *                 description: Array of image IDs in the new desired order
 *     responses:
 *       200:
 *         description: Image order updated successfully
 *         content:
 *           application/json:
 *             schema:
 *               type: object
 *               properties:
 *                 success:
 *                   type: boolean
 *                   example: true
 *                 message:
 *                   type: string
 *                   example: "Image order updated successfully"
 *                 data:
 *                   type: object
 *                   properties:
 *                     groupId:
 *                       type: string
 *                     updatedImages:
 *                       type: integer
 *                     newOrder:
 *                       type: array
 *                       items:
 *                         type: integer
 *       400:
 *         description: Invalid request - missing or invalid imageIds
 *       404:
 *         description: Group not found
 *       500:
 *         description: Server error during reordering
 */
router.put('/:groupId/reorder', async (req, res) => {
    /*
        #swagger.tags = ['Admin - Groups Moderation']
        #swagger.summary = 'Reorder images within a group'
        #swagger.parameters['groupId'] = {
            in: 'path',
            required: true,
            type: 'string',
            description: 'Admin groupId'
        }
        #swagger.responses[200] = { description: 'Order updated successfully' }
        #swagger.responses[400] = { description: 'Validation error' }
        #swagger.responses[404] = { description: 'Group not found' }
        #swagger.responses[500] = { description: 'Internal server error' }
    */
    try {
        const { groupId } = req.params;
        const { imageIds } = req.body;

        // Input validation
        if (!groupId) {
            return res.status(400).json({
                success: false,
                message: 'Group ID is required'
            });
        }

        if (!imageIds || !Array.isArray(imageIds) || imageIds.length === 0) {
            return res.status(400).json({
                success: false,
                message: 'imageIds array is required and cannot be empty'
            });
        }

        // Validate that all imageIds are numbers
        const invalidIds = imageIds.filter(id => !Number.isInteger(id) || id <= 0);
        if (invalidIds.length > 0) {
            return res.status(400).json({
                success: false,
                message: `Invalid image IDs: ${invalidIds.join(', ')}. Image IDs must be positive integers`
            });
        }

        // Log the reordering operation
        console.log(`[REORDER] Group ${groupId}: Reordering ${imageIds.length} images`);
        console.log(`[REORDER] New order: ${imageIds.join(' → ')}`);

        // Execute the reordering
        const result = await GroupRepository.updateImageOrder(groupId, imageIds);

        // Success response
        res.status(200).json({
            success: true,
            message: 'Image order updated successfully',
            data: result
        });

        // Log success
        console.log(`[REORDER] Success: Updated ${result.updatedImages} images in group ${groupId}`);

    } catch (error) {
        console.error(`[REORDER] Error reordering images in group ${req.params.groupId}:`, error.message);

        // Handle specific error types
        if (error.message.includes('not found')) {
            return res.status(404).json({
                success: false,
                message: error.message
            });
        }

        if (error.message.includes('Invalid image IDs') || 
            error.message.includes('Missing image IDs') ||
            error.message.includes('is required')) {
            return res.status(400).json({
                success: false,
                message: error.message
            });
        }

        // Generic server error
        res.status(500).json({
            success: false,
            message: 'Internal server error during image reordering',
            error: process.env.NODE_ENV === 'development' ? error.message : undefined
        });
    }
});

module.exports = router;