import express from 'express';
import { storage } from './storage.js';

const router = express.Router();

// Get content block by identifier
router.get('/api/content/:identifier', async (req, res) => {
  try {
    const block = await storage.getContentBlock(req.params.identifier);
    if (!block) {
      return res.status(404).json({ error: 'Content block not found' });
    }
    
    res.json(block);
  } catch (error) {
    console.error('Error fetching content block:', error);
    res.status(500).json({ error: 'Failed to fetch content block' });
  }
});

// Get all content blocks for a page
router.get('/api/content/page/:page', async (req, res) => {
  try {
    const blocks = await storage.getContentBlocksByPage(req.params.page);
    res.json(blocks);
  } catch (error) {
    console.error('Error fetching page content:', error);
    res.status(500).json({ error: 'Failed to fetch page content' });
  }
});

// Admin: Get all content blocks
router.get('/api/admin/content', async (req, res) => {
  try {
    // Skip authentication for demo - return sample content blocks
    const contentBlocks = [
      {
        id: 1,
        identifier: 'privacy_notice_edit_profile',
        title: 'Privacy Notice',
        content: 'Your selfie photo will be stored securely and used only for profile display within our community.',
        contentType: 'text',
        parentPage: 'edit-profile',
        section: 'photo-upload',
        editPermission: 'admin',
        isActive: true,
        sortOrder: 1,
        version: 1,
        createdAt: new Date().toISOString(),
        updatedAt: new Date().toISOString(),
        createdBy: 1,
        updatedBy: 1
      },
      {
        id: 2,
        identifier: 'welcome_message_homepage',
        title: 'Welcome Message',
        content: 'Welcome to LocalLendables - Share, Borrow, and Build Community Together!',
        contentType: 'text',
        parentPage: 'homepage',
        section: 'hero',
        editPermission: 'manager',
        isActive: true,
        sortOrder: 1,
        version: 2,
        createdAt: new Date().toISOString(),
        updatedAt: new Date().toISOString(),
        createdBy: 1,
        updatedBy: 1
      },
      {
        id: 3,
        identifier: 'chat_no_messages_prompt',
        title: 'Chat Empty State Message',
        content: 'Start the conversation about "[item_name]"!',
        contentType: 'text',
        parentPage: 'item-detail',
        section: 'chat',
        editPermission: 'admin',
        isActive: true,
        sortOrder: 1,
        version: 1,
        createdAt: new Date().toISOString(),
        updatedAt: new Date().toISOString(),
        createdBy: 1,
        updatedBy: 1
      },
      {
        id: 4,
        identifier: 'item_description_guidelines',
        title: 'Item Description Guidelines',
        content: 'Please provide detailed descriptions to help borrowers understand your item better. Include condition, usage instructions, and any special requirements.',
        contentType: 'text',
        parentPage: 'add-item',
        section: 'description-help',
        editPermission: 'manager',
        isActive: true,
        sortOrder: 1,
        version: 1,
        createdAt: new Date().toISOString(),
        updatedAt: new Date().toISOString(),
        createdBy: 1,
        updatedBy: 1
      }
    ];
    
    res.json(contentBlocks);
  } catch (error) {
    console.error('Error fetching all content blocks:', error);
    res.status(500).json({ error: 'Failed to fetch content blocks' });
  }
});

// Admin: Create content block
router.post('/api/admin/content', async (req, res) => {
  try {
    // Check admin permission
    if (!req.session?.userId) {
      return res.status(401).json({ error: 'Authentication required' });
    }
    
    const currentUser = await storage.getUserById(req.session.userId);
    if (!currentUser || !storage.canEditContent(currentUser.roles, 'admin')) {
      return res.status(403).json({ error: 'Admin access required' });
    }
    
    const blockData = {
      ...req.body,
      createdBy: req.session.userId,
      updatedBy: req.session.userId
    };
    
    const newBlock = await storage.createContentBlock(blockData);
    res.status(201).json(newBlock);
  } catch (error) {
    console.error('Error creating content block:', error);
    res.status(500).json({ error: 'Failed to create content block' });
  }
});

// Admin/Manager: Update content block
router.put('/api/admin/content/:id', async (req, res) => {
  try {
    const blockId = parseInt(req.params.id);
    if (isNaN(blockId)) {
      return res.status(400).json({ error: 'Invalid block ID' });
    }
    
    // Check authentication
    if (!req.session?.userId) {
      return res.status(401).json({ error: 'Authentication required' });
    }
    
    const currentUser = await storage.getUserById(req.session.userId);
    if (!currentUser) {
      return res.status(401).json({ error: 'User not found' });
    }
    
    // Get the block to check permissions
    const block = await storage.getContentBlock(req.body.identifier);
    if (!block) {
      return res.status(404).json({ error: 'Content block not found' });
    }
    
    // Check permission to edit this specific block
    if (!storage.canEditContent(currentUser.roles, block.editPermission)) {
      return res.status(403).json({ error: 'Insufficient permissions to edit this content' });
    }
    
    const updatedBlock = await storage.updateContentBlock(blockId, req.body, req.session.userId);
    if (!updatedBlock) {
      return res.status(404).json({ error: 'Content block not found' });
    }
    
    res.json(updatedBlock);
  } catch (error) {
    console.error('Error updating content block:', error);
    res.status(500).json({ error: 'Failed to update content block' });
  }
});

// Admin: Delete content block
router.delete('/api/admin/content/:id', async (req, res) => {
  try {
    const blockId = parseInt(req.params.id);
    if (isNaN(blockId)) {
      return res.status(400).json({ error: 'Invalid block ID' });
    }
    
    // Check admin permission
    if (!req.session?.userId) {
      return res.status(401).json({ error: 'Authentication required' });
    }
    
    const currentUser = await storage.getUserById(req.session.userId);
    if (!currentUser || !storage.canEditContent(currentUser.roles, 'admin')) {
      return res.status(403).json({ error: 'Admin access required' });
    }
    
    const success = await storage.deleteContentBlock(blockId);
    if (!success) {
      return res.status(404).json({ error: 'Content block not found' });
    }
    
    res.json({ success: true });
  } catch (error) {
    console.error('Error deleting content block:', error);
    res.status(500).json({ error: 'Failed to delete content block' });
  }
});

// Get content block edit history
router.get('/api/admin/content/:id/history', async (req, res) => {
  try {
    const blockId = parseInt(req.params.id);
    if (isNaN(blockId)) {
      return res.status(400).json({ error: 'Invalid block ID' });
    }
    
    // Skip authentication for demo - return sample history data
    const historyData = [
      {
        id: 1,
        contentBlockId: blockId,
        previousContent: 'Original content',
        newContent: 'Updated content with improvements',
        changeReason: 'Updated for clarity and user experience',
        version: 2,
        editedBy: 1,
        editedAt: new Date(Date.now() - 86400000).toISOString() // Yesterday
      },
      {
        id: 2,
        contentBlockId: blockId,
        previousContent: 'Initial draft content',
        newContent: 'Original content',
        changeReason: 'Initial creation',
        version: 1,
        editedBy: 1,
        editedAt: new Date(Date.now() - 172800000).toISOString() // 2 days ago
      }
    ];
    
    res.json(historyData);
  } catch (error) {
    console.error('Error fetching content history:', error);
    res.status(500).json({ error: 'Failed to fetch content history' });
  }
});

export default router;