import { Router, Response, NextFunction } from 'express'
import { body, validationResult } from 'express-validator'
import { db } from '../config/secureDatabase'
import { authenticate, AuthRequest } from '../middleware/auth'
import { requirePermission } from '../middleware/roleAuth'
import { logger } from '../utils/logger'

const router = Router()

// Get system settings
router.get('/', authenticate, requirePermission('settings:read'), async (req: AuthRequest, res: Response, next: NextFunction) => {
  try {
    const settings = db.prepare('SELECT key, value, description FROM system_settings').all() as any[]
    
    const settingsMap = settings.reduce((acc, setting) => {
      acc[setting.key] = {
        value: setting.value === 'true' || setting.value === 'false' ? setting.value === 'true' : setting.value,
        description: setting.description
      }
      return acc
    }, {})

    res.json({ success: true, data: settingsMap })
  } catch (error) {
    logger.error('Error fetching settings:', error)
    next(error)
  }
})

// Update system setting
router.put('/:key', 
  authenticate, 
  requirePermission('settings:update'),
  [
    body('value').notEmpty()
  ],
  async (req: AuthRequest, res: Response, next: NextFunction) => {
    try {
      const errors = validationResult(req)
      if (!errors.isEmpty()) {
        return res.status(400).json({ 
          success: false, 
          error: { message: 'Invalid input', details: errors.array() } 
        })
      }

      const { key } = req.params
      const { value } = req.body
      const now = new Date().toISOString()

      // Convert boolean to string for storage
      const stringValue = typeof value === 'boolean' ? value.toString() : value

      // Check if setting exists
      const existingSetting = db.prepare('SELECT key FROM system_settings WHERE key = ?').get(key)
      
      if (existingSetting) {
        // Update existing setting
        db.prepare(`
          UPDATE system_settings SET value = ?, updated_at = ?, updated_by = ?
          WHERE key = ?
        `).run(stringValue, now, req.user!.id, key)
        
        logger.info(`System setting ${key} updated to ${stringValue} by user ${req.user!.username}`)
      } else {
        // Create new setting
        db.prepare(`
          INSERT INTO system_settings (key, value, updated_at, updated_by)
          VALUES (?, ?, ?, ?)
        `).run(key, stringValue, now, req.user!.id)
        
        logger.info(`System setting ${key} created with value ${stringValue} by user ${req.user!.username}`)
      }

      res.json({ 
        success: true, 
        message: 'Setting updated successfully',
        data: { key, value: stringValue }
      })
    } catch (error) {
      logger.error('Error updating setting:', error)
      next(error)
    }
  }
)

export default router