import { Router, Response, NextFunction } from 'express'
import { v4 as uuidv4 } from 'uuid'
import { body, validationResult } from 'express-validator'
import bcrypt from 'bcrypt'
import { db, encryptedDb } from '../config/secureDatabase'
import { authenticate, authorize, AuthRequest } from '../middleware/auth'
import { requirePermission, requireEditPermission } from '../middleware/roleAuth'
import { Employee, LanguageSkill, Skill, UserRole } from '@skillmate/shared'
import { syncService } from '../services/syncService'
import { FieldEncryption } from '../services/encryption'
import { emailService } from '../services/emailService'
import { logger } from '../utils/logger'

const router = Router()

// Helper function to map old proficiency to new level
function mapProficiencyToLevel(proficiency: string): 'basic' | 'fluent' | 'native' | 'business' {
  const mapping: Record<string, 'basic' | 'fluent' | 'native' | 'business'> = {
    'A1': 'basic',
    'A2': 'basic',
    'B1': 'business',
    'B2': 'business',
    'C1': 'fluent',
    'C2': 'fluent',
    'Muttersprache': 'native',
    'native': 'native',
    'fluent': 'fluent',
    'advanced': 'business',
    'intermediate': 'business',
    'basic': 'basic'
  }
  return mapping[proficiency] || 'basic'
}

// Log security audit events
function logSecurityAudit(
  action: string,
  entityType: string,
  entityId: string,
  userId: string,
  req: AuthRequest,
  riskLevel: 'low' | 'medium' | 'high' | 'critical' = 'low'
) {
  try {
    db.prepare(`
      INSERT INTO security_audit_log (
        id, entity_type, entity_id, action, user_id, 
        timestamp, ip_address, user_agent, risk_level
      ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
    `).run(
      uuidv4(),
      entityType,
      entityId,
      action,
      userId,
      new Date().toISOString(),
      req.ip || req.connection.remoteAddress,
      req.get('user-agent'),
      riskLevel
    )
  } catch (error) {
    logger.error('Failed to log security audit:', error)
  }
}

// Get all employees
router.get('/', authenticate, requirePermission('employees:read'), async (req: AuthRequest, res, next) => {
  try {
    const { unitId, includeDescendants } = (req.query || {}) as any

    // Optional filter by unit (including descendants)
    let allowedIds: Set<string> | null = null
    if (unitId) {
      const collectDescendants = (rootId: string): string[] => {
        const ids: string[] = [rootId]
        const stack: string[] = [rootId]
        while (stack.length) {
          const curr = stack.pop()!
          const children = db.prepare('SELECT id FROM organizational_units WHERE parent_id = ?').all(curr) as any[]
          for (const ch of children) {
            ids.push(ch.id)
            stack.push(ch.id)
          }
        }
        return ids
      }
      const unitIds = includeDescendants === '1' || includeDescendants === 'true'
        ? collectDescendants(String(unitId))
        : [String(unitId)]
      const rows = db.prepare(`SELECT id FROM employees WHERE primary_unit_id IN (${unitIds.map(() => '?').join(',')})`).all(...unitIds) as any[]
      allowedIds = new Set(rows.map(r => r.id))
    }

    const employees = encryptedDb.getAllEmployees().filter((e: any) => !allowedIds || allowedIds.has(e.id))

    const employeesWithDetails = employees.map((emp: any) => {
      // Get skills
      const skills = db.prepare(`
        SELECT s.id, s.name, s.category, es.level, es.verified, es.verified_by, es.verified_date
        FROM employee_skills es
        JOIN skills s ON es.skill_id = s.id
        WHERE es.employee_id = ?
      `).all(emp.id)

      // Get languages
      const languages = db.prepare(`
        SELECT language, proficiency, certified, certificate_type, is_native, can_interpret
        FROM language_skills
        WHERE employee_id = ?
      `).all(emp.id)

      // Get specializations
      const specializations = db.prepare(`
        SELECT name FROM specializations WHERE employee_id = ?
      `).all(emp.id).map((s: any) => s.name)

      const employee: Employee = {
        id: emp.id,
        firstName: emp.first_name,
        lastName: emp.last_name,
        employeeNumber: (emp.employee_number && !String(emp.employee_number).startsWith('EMP')) ? emp.employee_number : undefined,
        photo: emp.photo,
        position: emp.position,
        officialTitle: emp.official_title || undefined,
        department: emp.department,
        email: emp.email,
        phone: emp.phone,
        mobile: emp.mobile,
        office: emp.office,
        availability: emp.availability,
        skills: skills.map((s: any) => ({
          id: s.id,
          name: s.name,
          category: s.category,
          level: s.level,
          verified: Boolean(s.verified),
          verifiedBy: s.verified_by,
          verifiedDate: s.verified_date ? new Date(s.verified_date) : undefined
        })),
        languages: languages.map((l: any) => ({
          code: l.language,
          level: mapProficiencyToLevel(l.proficiency)
        })),
        clearance: emp.clearance_level && emp.clearance_valid_until && emp.clearance_issued_date ? {
          level: emp.clearance_level,
          validUntil: new Date(emp.clearance_valid_until),
          issuedDate: new Date(emp.clearance_issued_date)
        } : undefined,
        specializations,
        createdAt: new Date(emp.created_at),
        updatedAt: new Date(emp.updated_at),
        createdBy: emp.created_by,
        updatedBy: emp.updated_by
      }

      return employee
    })

    // Log read access
    logSecurityAudit('read', 'employees', 'all', req.user!.id, req, 'low')

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

// Public employees for frontend: only those with a linked user (excluding admin)
router.get('/public', authenticate, async (req: AuthRequest, res, next) => {
  try {
    // Get allowed employee IDs from users table (exclude admin, only active accounts)
    const allowedUserLinks = db.prepare(`
      SELECT employee_id FROM users
      WHERE employee_id IS NOT NULL AND username <> 'admin' AND is_active = 1
    `).all() as any[]
    const allowedIds = new Set((allowedUserLinks || []).map((u: any) => u.employee_id))

    const employees = encryptedDb.getAllEmployees()
      .filter((emp: any) => allowedIds.has(emp.id))

    const employeesWithDetails = employees.map((emp: any) => {
      const skills = db.prepare(`
        SELECT s.id, s.name, s.category, es.level, es.verified, es.verified_by, es.verified_date
        FROM employee_skills es
        JOIN skills s ON es.skill_id = s.id
        WHERE es.employee_id = ?
      `).all(emp.id)

      const languages = db.prepare(`
        SELECT language, proficiency, certified, certificate_type, is_native, can_interpret
        FROM language_skills
        WHERE employee_id = ?
      `).all(emp.id)

      const specializations = db.prepare(`
        SELECT name FROM specializations WHERE employee_id = ?
      `).all(emp.id).map((s: any) => s.name)

      const employee: Employee = {
        id: emp.id,
        firstName: emp.first_name,
        lastName: emp.last_name,
        employeeNumber: (emp.employee_number && !String(emp.employee_number).startsWith('EMP')) ? emp.employee_number : undefined,
        photo: emp.photo,
        position: emp.position,
        officialTitle: emp.official_title || undefined,
        department: emp.department,
        email: emp.email,
        phone: emp.phone,
        mobile: emp.mobile,
        office: emp.office,
        availability: emp.availability,
        skills: skills.map((s: any) => ({
          id: s.id,
          name: s.name,
          category: s.category,
          level: s.level,
          verified: Boolean(s.verified),
          verifiedBy: s.verified_by,
          verifiedDate: s.verified_date ? new Date(s.verified_date) : undefined
        })),
        languages: languages.map((l: any) => ({
          code: l.language,
          level: mapProficiencyToLevel(l.proficiency)
        })),
        clearance: emp.clearance_level && emp.clearance_valid_until && emp.clearance_issued_date ? {
          level: emp.clearance_level,
          validUntil: new Date(emp.clearance_valid_until),
          issuedDate: new Date(emp.clearance_issued_date)
        } : undefined,
        specializations,
        createdAt: new Date(emp.created_at),
        updatedAt: new Date(emp.updated_at),
        createdBy: emp.created_by,
        updatedBy: emp.updated_by
      }

      return employee
    })

    res.json({ success: true, data: employeesWithDetails })
  } catch (error) {
    logger.error('Error fetching public employees:', error)
    next(error)
  }
})

// Get employee by ID
router.get('/:id', authenticate, requirePermission('employees:read'), async (req: AuthRequest, res, next) => {
  try {
    const { id } = req.params

    const emp = encryptedDb.getEmployee(id)

    if (!emp) {
      return res.status(404).json({ 
        success: false, 
        error: { message: 'Employee not found' } 
      })
    }

    // Get skills
    const skills = db.prepare(`
      SELECT s.id, s.name, s.category, es.level, es.verified, es.verified_by, es.verified_date
      FROM employee_skills es
      JOIN skills s ON es.skill_id = s.id
      WHERE es.employee_id = ?
    `).all(emp.id)

    // Get languages
    const languages = db.prepare(`
      SELECT language, proficiency, certified, certificate_type, is_native, can_interpret
      FROM language_skills
      WHERE employee_id = ?
    `).all(emp.id)

    // Get specializations
    const specializations = db.prepare(`
      SELECT name FROM specializations WHERE employee_id = ?
    `).all(emp.id).map((s: any) => s.name)

    const employee: Employee = {
      id: emp.id,
      firstName: emp.first_name,
      lastName: emp.last_name,
      employeeNumber: (emp.employee_number && !String(emp.employee_number).startsWith('EMP')) ? emp.employee_number : undefined,
      photo: emp.photo,
      position: emp.position,
      officialTitle: emp.official_title || undefined,
      department: emp.department,
      email: emp.email,
      phone: emp.phone,
      mobile: emp.mobile,
      office: emp.office,
      availability: emp.availability,
      skills: skills.map((s: any) => ({
        id: s.id,
        name: s.name,
        category: s.category,
        level: s.level,
        verified: Boolean(s.verified),
        verifiedBy: s.verified_by,
        verifiedDate: s.verified_date ? new Date(s.verified_date) : undefined
      })),
      languages: languages.map((l: any) => ({
        code: l.language,
        level: mapProficiencyToLevel(l.proficiency)
      })),
      clearance: emp.clearance_level && emp.clearance_valid_until && emp.clearance_issued_date ? {
        level: emp.clearance_level,
        validUntil: new Date(emp.clearance_valid_until),
        issuedDate: new Date(emp.clearance_issued_date)
      } : undefined,
      specializations,
      createdAt: new Date(emp.created_at),
      updatedAt: new Date(emp.updated_at),
      createdBy: emp.created_by,
      updatedBy: emp.updated_by
    }

    // Log read access
    logSecurityAudit('read', 'employees', id, req.user!.id, req, 'low')

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

// Create employee (admin/poweruser only)
router.post('/', 
  authenticate,
  requirePermission('employees:create'),
  [
    body('firstName').notEmpty().trim().escape(),
    body('lastName').notEmpty().trim().escape(),
    body('email').isEmail().normalizeEmail(),
    body('department').notEmpty().trim().escape(),
    body('position').optional().trim().escape(),  // Optional
    body('phone').optional().trim(),  // Optional - kann später ergänzt werden
    body('employeeNumber').optional().trim()  // Optional - wird automatisch generiert wenn leer
  ],
  async (req: AuthRequest, res: Response, next: NextFunction) => {
    const transaction = db.transaction(() => {
      try {
        const errors = validationResult(req)
        if (!errors.isEmpty()) {
          return res.status(400).json({ 
            success: false, 
            error: { message: 'Invalid input', details: errors.array() } 
          })
        }

        const employeeId = uuidv4()
        const now = new Date().toISOString()

        const {
          firstName, lastName, employeeNumber, photo, position = 'Teammitglied', officialTitle,
          department, email, phone = 'Nicht angegeben', mobile, office, availability = 'available',
          clearance, skills = [], languages = [], specializations = [], userRole, createUser,
          primaryUnitId, assignmentRole
        } = req.body

        // Generate employee number if not provided
        const finalEmployeeNumber = employeeNumber || `EMP${Date.now()}`

        // Check if employee number already exists
        const existingEmployee = db.prepare('SELECT id FROM employees WHERE employee_number = ?').get(finalEmployeeNumber)
        if (existingEmployee) {
          return res.status(409).json({
            success: false,
            error: { message: 'Employee number already exists' }
          })
        }

        // Insert employee with encrypted fields
        encryptedDb.insertEmployee({
          id: employeeId,
          first_name: firstName,
          last_name: lastName,
          employee_number: finalEmployeeNumber,
          photo: photo || null,
          position,
          official_title: officialTitle || null,
          department,
          email,
          phone,
          mobile: mobile || null,
          office: office || null,
          availability,
          clearance_level: clearance?.level || null,
          clearance_valid_until: clearance?.validUntil || null,
          clearance_issued_date: clearance?.issuedDate || null,
          primary_unit_id: primaryUnitId || null,
          created_at: now,
          updated_at: now,
          created_by: req.user!.id
        })

        // Create primary assignment if provided
        if (primaryUnitId) {
          const unit = db.prepare('SELECT id, type FROM organizational_units WHERE id = ?').get(primaryUnitId)
          if (!unit) {
            return res.status(400).json({ success: false, error: { message: 'Invalid primary unit' } })
          }
          db.prepare(`
            INSERT INTO employee_unit_assignments (
              id, employee_id, unit_id, role, start_date, end_date, is_primary, created_at, updated_at
            ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
          `).run(
            uuidv4(), employeeId, primaryUnitId, assignmentRole || 'mitarbeiter',
            now, null, 1, now, now
          )
        }

        // Insert skills (only if they exist in skills table)
        if (skills && skills.length > 0) {
          const insertSkill = db.prepare(`
            INSERT INTO employee_skills (employee_id, skill_id, level, verified, verified_by, verified_date)
            VALUES (?, ?, ?, ?, ?, ?)
          `)
          
          const checkSkillExists = db.prepare('SELECT id FROM skills WHERE id = ?')

          for (const skill of skills) {
            // Check if skill exists before inserting
            const skillExists = checkSkillExists.get(skill.id)
            if (skillExists) {
              insertSkill.run(
                employeeId,
                skill.id,
                skill.level || null,
                skill.verified ? 1 : 0,
                skill.verifiedBy || null,
                skill.verifiedDate || null
              )
            } else {
              logger.warn(`Skill with ID ${skill.id} does not exist in skills table, skipping`)
            }
          }
        }

        // Insert languages
        if (languages && languages.length > 0) {
          const insertLang = db.prepare(`
            INSERT INTO language_skills (
              id, employee_id, language, proficiency, certified, 
              certificate_type, is_native, can_interpret
            ) VALUES (?, ?, ?, ?, ?, ?, ?, ?)
          `)

          for (const lang of languages) {
            insertLang.run(
              uuidv4(),
              employeeId,
              lang.code || lang.language,
              lang.level || lang.proficiency || 'basic',
              lang.certified ? 1 : 0,
              lang.certificateType || null,
              lang.isNative ? 1 : 0,
              lang.canInterpret ? 1 : 0
            )
          }
        }

        // Insert specializations
        if (specializations && specializations.length > 0) {
          const insertSpec = db.prepare(`
            INSERT INTO specializations (id, employee_id, name)
            VALUES (?, ?, ?)
          `)

          for (const spec of specializations) {
            insertSpec.run(uuidv4(), employeeId, spec)
          }
        }

        // Create user account if requested
        let userId = null
        let tempPassword = null
        if (createUser) {
          userId = uuidv4()
          tempPassword = `Temp${Math.random().toString(36).slice(-8)}!@#`
          const hashedPassword = bcrypt.hashSync(tempPassword, 12)
          // Enforce role policy: only admins may assign roles; others default to 'user'
          const assignedRole = req.user?.role === 'admin' && userRole ? userRole : 'user'
          
          db.prepare(`
            INSERT INTO users (id, username, email, email_hash, password, role, employee_id, is_active, created_at, updated_at)
            VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
          `).run(
            userId,
            email,
            FieldEncryption.encrypt(email),
            FieldEncryption.hash(email),
            hashedPassword,
            assignedRole,
            employeeId,
            1,
            now,
            now
          )
          
          logger.info(`User created for employee ${firstName} ${lastName} with role ${userRole}`)
        }

        // Log creation
        logSecurityAudit('create', 'employees', employeeId, req.user!.id, req, 'medium')

        // Queue sync for new employee
        const newEmployee = {
          id: employeeId,
          firstName,
          lastName,
          employeeNumber: finalEmployeeNumber,
          photo: photo || null,
          position,
          officialTitle: officialTitle || null,
          department,
          email,
          phone,
          mobile: mobile || null,
          office: office || null,
          availability,
          clearance,
          primaryUnitId: primaryUnitId || null,
          skills,
          languages,
          specializations,
          createdAt: now,
          updatedAt: now,
          createdBy: req.user!.id
        }
        
        syncService.queueSync('employees', 'create', newEmployee).catch(err => {
          logger.error('Failed to queue sync:', err)
        })

        return res.status(201).json({ 
          success: true, 
          data: { 
            id: employeeId,
            userId: userId,
            temporaryPassword: tempPassword
          },
          message: `Employee created successfully${createUser ? ' with user account' : ''}` 
        })
      } catch (error) {
        logger.error('Error creating employee:', error)
        throw error
      }
    })

    try {
      const result = transaction()
      
      // Send email after successful transaction (if user was created)
      const { createUser, userRole, email, firstName } = req.body
      if (createUser && userRole && result && (result as any).data?.userId && (result as any).data?.temporaryPassword) {
        // Check if email notifications are enabled
        const emailNotificationsSetting = db.prepare('SELECT value FROM system_settings WHERE key = ?').get('email_notifications_enabled') as any
        const emailNotificationsEnabled = emailNotificationsSetting?.value === 'true'

        // Send initial password via email if notifications are enabled
        if (emailNotificationsEnabled && emailService.isServiceEnabled()) {
          const emailSent = await emailService.sendInitialPassword(email, (result as any).data.temporaryPassword, firstName)
          if (emailSent) {
            logger.info(`Initial password email sent to ${email}`)
          } else {
            logger.warn(`Failed to send initial password email to ${email}`)
          }
        }
      }
      
      return result
    } catch (error: any) {
      logger.error('Transaction failed:', error)
      return res.status(500).json({
        success: false,
        error: { 
          message: 'Failed to create employee',
          details: process.env.NODE_ENV === 'development' ? error.message : undefined
        }
      })
    }
  }
)

// Update employee
router.put('/:id',
  authenticate,
  requireEditPermission(req => req.params.id),
  [
    body('firstName').notEmpty().trim().escape(),
    body('lastName').notEmpty().trim().escape(),
    body('position').optional().trim().escape(),
    body('officialTitle').optional().trim().escape(),
    body('department').notEmpty().trim().escape(),
    body('email').isEmail().normalizeEmail(),
    body('phone').optional().trim(),
    body('employeeNumber').optional().trim(),
    body('availability').optional().isIn(['available', 'parttime', 'unavailable', 'busy', 'away', 'vacation', 'sick', 'training', 'operation'])
  ],
  async (req: AuthRequest, res: Response, next: NextFunction) => {
    const transaction = db.transaction(() => {
      try {
        const errors = validationResult(req)
        if (!errors.isEmpty()) {
          return res.status(400).json({ 
            success: false, 
            error: { message: 'Invalid input', details: errors.array() } 
          })
        }

        const { id } = req.params
        const now = new Date().toISOString()

        const {
          firstName, lastName, position = 'Teammitglied', officialTitle, department, email, phone = 'Nicht angegeben', 
          mobile, office, availability = 'available', clearance, skills, languages, specializations,
          employeeNumber
        } = req.body

        // Check if employee exists
        const existing = db.prepare('SELECT id FROM employees WHERE id = ?').get(id)
        if (!existing) {
          return res.status(404).json({ 
            success: false, 
            error: { message: 'Employee not found' } 
          })
        }

        // Update employee with encrypted fields
        db.prepare(`
          UPDATE employees SET
            first_name = ?, last_name = ?, position = ?, official_title = ?, department = ?,
            email = ?, email_hash = ?, phone = ?, phone_hash = ?, 
            mobile = ?, office = ?, availability = ?,
            clearance_level = ?, clearance_valid_until = ?, clearance_issued_date = ?,
            updated_at = ?, updated_by = ?
          WHERE id = ?
        `).run(
          firstName, lastName, position, officialTitle || null, department,
          FieldEncryption.encrypt(email),
          FieldEncryption.hash(email),
          FieldEncryption.encrypt(phone || ''),
          FieldEncryption.hash(phone || ''),
          mobile ? FieldEncryption.encrypt(mobile) : null,
          office || null,
          availability,
          clearance?.level || null,
          clearance?.validUntil || null,
          clearance?.issuedDate || null,
          now,
          req.user!.id,
          id
        )

        // Optionally update employee number (NW-Kennung) with uniqueness check
        if (employeeNumber && typeof employeeNumber === 'string') {
          const existsNumber = db.prepare('SELECT id FROM employees WHERE employee_number = ? AND id <> ?').get(employeeNumber, id)
          if (existsNumber) {
            return res.status(409).json({ success: false, error: { message: 'Employee number already exists' } })
          }
          db.prepare('UPDATE employees SET employee_number = ?, updated_at = ?, updated_by = ? WHERE id = ?')
            .run(employeeNumber, now, req.user!.id, id)
        }

        // Update skills
        if (skills !== undefined) {
          // Delete existing skills
          db.prepare('DELETE FROM employee_skills WHERE employee_id = ?').run(id)
          
          // Insert new skills
          if (skills.length > 0) {
            const insertSkill = db.prepare(`
              INSERT INTO employee_skills (employee_id, skill_id, level, verified, verified_by, verified_date)
              VALUES (?, ?, ?, ?, ?, ?)
            `)
            const checkSkillExists = db.prepare('SELECT id FROM skills WHERE id = ?')

            for (const skill of skills) {
              const exists = checkSkillExists.get(skill.id)
              if (!exists) {
                logger.warn(`Skill with ID ${skill.id} does not exist in skills table, skipping`)
                continue
              }
              insertSkill.run(
                id,
                skill.id,
                typeof skill.level === 'number' ? skill.level : (parseInt(skill.level) || null),
                skill.verified ? 1 : 0,
                skill.verifiedBy || null,
                skill.verifiedDate || null
              )
            }
          }
        }

        // Log update
        logSecurityAudit('update', 'employees', id, req.user!.id, req, 'medium')

        // Queue sync for updated employee
        const updatedEmployee = {
          id,
          firstName,
          lastName,
          position,
          officialTitle: officialTitle || null,
          department,
          email,
          phone,
          mobile: mobile || null,
          office: office || null,
          availability,
          clearance,
          skills,
          languages,
          specializations,
          updatedAt: now,
          updatedBy: req.user!.id
        }
        
        syncService.queueSync('employees', 'update', updatedEmployee).catch(err => {
          logger.error('Failed to queue sync:', err)
        })

        return res.json({ 
          success: true, 
          message: 'Employee updated successfully' 
        })
      } catch (error) {
        logger.error('Error updating employee:', error)
        throw error
      }
    })

    try {
      return transaction()
    } catch (error: any) {
      logger.error('Transaction failed:', error)
      return res.status(500).json({
        success: false,
        error: { 
          message: 'Failed to update employee',
          details: process.env.NODE_ENV === 'development' ? error.message : undefined
        }
      })
    }
  }
)

// Delete employee (admin only)
router.delete('/:id',
  authenticate,
  requirePermission('employees:delete'),
  async (req: AuthRequest, res: Response, next: NextFunction) => {
    const transaction = db.transaction(() => {
      try {
        const { id } = req.params

        // Check if employee exists
        const existing = db.prepare('SELECT id FROM employees WHERE id = ?').get(id)
        if (!existing) {
          return res.status(404).json({ 
            success: false, 
            error: { message: 'Employee not found' } 
          })
        }

        // Delete employee and related data
        db.prepare('DELETE FROM employee_skills WHERE employee_id = ?').run(id)
        db.prepare('DELETE FROM language_skills WHERE employee_id = ?').run(id)
        db.prepare('DELETE FROM specializations WHERE employee_id = ?').run(id)
        db.prepare('DELETE FROM employees WHERE id = ?').run(id)

        // Log deletion
        logSecurityAudit('delete', 'employees', id, req.user!.id, req, 'high')

        // Queue sync for deleted employee
        syncService.queueSync('employees', 'delete', { id }).catch(err => {
          logger.error('Failed to queue sync:', err)
        })

        return res.json({ 
          success: true, 
          message: 'Employee deleted successfully' 
        })
      } catch (error) {
        logger.error('Error deleting employee:', error)
        throw error
      }
    })

    try {
      return transaction()
    } catch (error: any) {
      logger.error('Transaction failed:', error)
      return res.status(500).json({
        success: false,
        error: { 
          message: 'Failed to delete employee',
          details: process.env.NODE_ENV === 'development' ? error.message : undefined
        }
      })
    }
  }
)

// Search employees by skills
router.post('/search', authenticate, requirePermission('employees:read'), async (req: AuthRequest, res, next) => {
  try {
    const { skills, category } = req.body

    let query = `
      SELECT DISTINCT e.id, e.first_name, e.last_name, e.employee_number, 
             e.position, e.department, e.availability,
             e.email, e.phone, e.mobile
      FROM employees e
      JOIN employee_skills es ON e.id = es.employee_id
      JOIN skills s ON es.skill_id = s.id
      WHERE 1=1
    `

    const params: any[] = []

    if (skills && skills.length > 0) {
      const placeholders = skills.map(() => '?').join(',')
      query += ` AND s.name IN (${placeholders})`
      params.push(...skills)
    }

    if (category) {
      query += ` AND s.category = ?`
      params.push(category)
    }

    query += ` ORDER BY e.last_name, e.first_name`

    const results = db.prepare(query).all(...params)

    // Decrypt sensitive fields in results safely
    const decryptedResults = results.map((emp: any) => {
      const safeDecrypt = (v: any) => {
        try { return v ? FieldEncryption.decrypt(v) : null } catch { return null }
      }
      return {
        ...emp,
        email: safeDecrypt(emp.email),
        phone: safeDecrypt(emp.phone),
        mobile: safeDecrypt(emp.mobile),
      }
    })

    res.json({ success: true, data: decryptedResults })
  } catch (error) {
    logger.error('Error searching employees:', error)
    next(error)
  }
})

export default router
