import { Router } from 'express'
import { v4 as uuidv4 } from 'uuid'
import { db } from '../config/secureDatabase'
import { authenticate, AuthRequest } from '../middleware/auth'
import { logger } from '../utils/logger'

const router = Router()

// Get employee's current organization unit
router.get('/employee/:employeeId/organization', authenticate, async (req: AuthRequest, res, next) => {
  try {
    const { employeeId } = req.params
    
    // Check if user can access this employee's data
    if (req.user?.employeeId !== employeeId && req.user?.role !== 'admin' && req.user?.role !== 'superuser') {
      return res.status(403).json({ success: false, error: { message: 'Access denied' } })
    }
    
    const unit = db.prepare(`
      SELECT 
        ou.id, ou.code, ou.name, ou.type, ou.level,
        eua.role, eua.is_primary as isPrimary,
        eua.start_date as startDate
      FROM employee_unit_assignments eua
      JOIN organizational_units ou ON ou.id = eua.unit_id
      WHERE eua.employee_id = ? 
        AND eua.is_primary = 1
        AND (eua.end_date IS NULL OR eua.end_date > datetime('now'))
        AND ou.is_active = 1
      ORDER BY eua.start_date DESC
      LIMIT 1
    `).get(employeeId)
    
    if (!unit) {
      return res.json({ success: true, data: null })
    }
    
    res.json({ success: true, data: unit })
  } catch (error) {
    logger.error('Error fetching employee organization:', error)
    next(error)
  }
})

// Update employee's organization unit (simplified endpoint)
router.put('/employee/:employeeId/organization', authenticate, async (req: AuthRequest, res: any, next: any) => {
  try {
    const { employeeId } = req.params
    const { unitId } = req.body
    
    // Check permissions
    if (req.user?.employeeId !== employeeId && req.user?.role !== 'admin' && req.user?.role !== 'superuser') {
      return res.status(403).json({ success: false, error: { message: 'Access denied' } })
    }
    
    const now = new Date().toISOString()
    
    // Start transaction
    const transaction = db.transaction(() => {
      // End all current assignments for this employee
      db.prepare(`
        UPDATE employee_unit_assignments
        SET end_date = ?, updated_at = ?
        WHERE employee_id = ? AND end_date IS NULL
      `).run(now, now, employeeId)
      
      // If unitId provided, create new assignment
      if (unitId) {
        // Verify unit exists
        const unit = db.prepare('SELECT id FROM organizational_units WHERE id = ? AND is_active = 1').get(unitId)
        if (!unit) {
          throw new Error('Unit not found')
        }
        
        const assignmentId = uuidv4()
        db.prepare(`
          INSERT INTO employee_unit_assignments (
            id, employee_id, unit_id, role,
            start_date, is_primary, created_at, updated_at
          ) VALUES (?, ?, ?, ?, ?, ?, ?, ?)
        `).run(
          assignmentId, employeeId, unitId, 'mitarbeiter',
          now, 1, now, now
        )
      }
      
      // Update employee's department field for backward compatibility
      if (unitId) {
        const unitInfo = db.prepare('SELECT name FROM organizational_units WHERE id = ?').get(unitId) as any
        if (unitInfo) {
          db.prepare(`
            UPDATE employees 
            SET department = ?, updated_at = ?
            WHERE id = ?
          `).run(unitInfo.name, now, employeeId)
        }
      } else {
        // Clear department if no unit
        db.prepare(`
          UPDATE employees 
          SET department = NULL, updated_at = ?
          WHERE id = ?
        `).run(now, employeeId)
      }
    })
    
    try {
      transaction()
      res.json({ success: true, message: 'Organization updated successfully' })
    } catch (error: any) {
      if (error.message === 'Unit not found') {
        return res.status(404).json({ success: false, error: { message: 'Unit not found' } })
      }
      throw error
    }
  } catch (error) {
    logger.error('Error updating employee organization:', error)
    next(error)
  }
})

// Get all employees in a unit (for managers)
router.get('/unit/:unitId/employees', authenticate, async (req: AuthRequest, res, next) => {
  try {
    const { unitId } = req.params
    
    // Check if user is a manager of this unit or admin
    const isManager = db.prepare(`
      SELECT 1 FROM employee_unit_assignments
      WHERE employee_id = ? AND unit_id = ? 
        AND role IN ('leiter', 'stellvertreter')
        AND (end_date IS NULL OR end_date > datetime('now'))
    `).get(req.user?.employeeId, unitId)
    
    if (!isManager && req.user?.role !== 'admin' && req.user?.role !== 'superuser') {
      return res.status(403).json({ success: false, error: { message: 'Access denied' } })
    }
    
    const employees = db.prepare(`
      SELECT 
        e.id, e.first_name as firstName, e.last_name as lastName,
        e.position, e.email, e.phone, e.photo,
        eua.role, eua.is_primary as isPrimary,
        eua.start_date as startDate
      FROM employee_unit_assignments eua
      JOIN employees e ON e.id = eua.employee_id
      WHERE eua.unit_id = ? 
        AND (eua.end_date IS NULL OR eua.end_date > datetime('now'))
      ORDER BY 
        CASE eua.role 
          WHEN 'leiter' THEN 1
          WHEN 'stellvertreter' THEN 2
          WHEN 'beauftragter' THEN 3
          ELSE 4
        END,
        e.last_name, e.first_name
    `).all(unitId)
    
    res.json({ success: true, data: employees })
  } catch (error) {
    logger.error('Error fetching unit employees:', error)
    next(error)
  }
})

export default router