import { Router } from 'express'
import multer from 'multer'
import path from 'path'
import fs from 'fs'
import { v4 as uuidv4 } from 'uuid'
import { authenticate, AuthRequest } from '../middleware/auth'
import { db } from '../config/database'

const router = Router()

// Ensure upload directory exists
const uploadDir = path.join(__dirname, '../../uploads/photos')
if (!fs.existsSync(uploadDir)) {
  fs.mkdirSync(uploadDir, { recursive: true })
}

// Configure multer for photo uploads
const storage = multer.diskStorage({
  destination: (req, file, cb) => {
    cb(null, uploadDir)
  },
  filename: (req, file, cb) => {
    const ext = path.extname(file.originalname)
    const filename = `${uuidv4()}${ext}`
    cb(null, filename)
  }
})

const upload = multer({
  storage,
  limits: {
    fileSize: 5 * 1024 * 1024 // 5MB limit
  },
  fileFilter: (req, file, cb) => {
    const allowedTypes = /jpeg|jpg|png|gif|webp/
    const extname = allowedTypes.test(path.extname(file.originalname).toLowerCase())
    const mimetype = allowedTypes.test(file.mimetype)
    
    if (mimetype && extname) {
      return cb(null, true)
    } else {
      cb(new Error('Only image files are allowed'))
    }
  }
})

// Upload employee photo
// Only the user themself may change their own photo (no admin/superuser override)
router.post('/employee-photo/:employeeId', 
  authenticate, 
  (req: AuthRequest, res, next) => {
    if (!req.user || req.user.employeeId !== req.params.employeeId) {
      return res.status(403).json({ success: false, error: { message: 'Only the profile owner may change the photo' } })
    }
    next()
  },
  upload.single('photo'),
  async (req: AuthRequest, res, next) => {
    try {
      if (!req.file) {
        return res.status(400).json({ 
          success: false, 
          error: { message: 'No file uploaded' } 
        })
      }

      const { employeeId } = req.params
      
      // Check if employee exists
      const employee = db.prepare('SELECT id, photo FROM employees WHERE id = ?').get(employeeId) as any
      if (!employee) {
        // Delete uploaded file
        fs.unlinkSync(req.file.path)
        return res.status(404).json({ 
          success: false, 
          error: { message: 'Employee not found' } 
        })
      }

      // Delete old photo if exists
      if (employee.photo) {
        const oldPhotoPath = path.join(uploadDir, path.basename(employee.photo))
        if (fs.existsSync(oldPhotoPath)) {
          fs.unlinkSync(oldPhotoPath)
        }
      }

      // Update employee photo URL
      const photoUrl = `/uploads/photos/${req.file.filename}`
      db.prepare('UPDATE employees SET photo = ?, updated_at = ?, updated_by = ? WHERE id = ?')
        .run(photoUrl, new Date().toISOString(), req.user!.id, employeeId)

      res.json({ 
        success: true, 
        data: { photoUrl },
        message: 'Photo uploaded successfully' 
      })
    } catch (error) {
      // Clean up uploaded file on error
      if (req.file && fs.existsSync(req.file.path)) {
        fs.unlinkSync(req.file.path)
      }
      next(error)
    }
  }
)

// Delete employee photo
router.delete('/employee-photo/:employeeId',
  authenticate,
  (req: AuthRequest, res, next) => {
    if (!req.user || req.user.employeeId !== req.params.employeeId) {
      return res.status(403).json({ success: false, error: { message: 'Only the profile owner may delete the photo' } })
    }
    next()
  },
  async (req: AuthRequest, res, next) => {
    try {
      const { employeeId } = req.params
      
      // Get employee photo
      const employee = db.prepare('SELECT id, photo FROM employees WHERE id = ?').get(employeeId) as any
      if (!employee) {
        return res.status(404).json({ 
          success: false, 
          error: { message: 'Employee not found' } 
        })
      }

      if (employee.photo) {
        const photoPath = path.join(uploadDir, path.basename(employee.photo))
        if (fs.existsSync(photoPath)) {
          fs.unlinkSync(photoPath)
        }
      }

      // Clear photo from database
      db.prepare('UPDATE employees SET photo = NULL, updated_at = ?, updated_by = ? WHERE id = ?')
        .run(new Date().toISOString(), req.user!.id, employeeId)

      res.json({ 
        success: true, 
        message: 'Photo deleted successfully' 
      })
    } catch (error) {
      next(error)
    }
  }
)

export default router
