import { Router } from 'express';
import { Attendance, User } from '../models/index.js';
import { requireAuth, requireRole } from '../middleware/auth.js';
import { sendError } from '../util/httpError.js';
import { Op } from 'sequelize';

const router = Router();

// Middleware to check if user is on Workshop WiFi (IP validation)
const validateWorkshopIP = (req, res, next) => {
  const allowedIPs = (process.env.WORKSHOP_IPS || '127.0.0.1,::1,192.168.29.141').split(',');
  const clientIP = req.ip || req.connection.remoteAddress;
  
  // Clean IPv6 prefix for local addresses
  const cleanIP = clientIP.replace(/^::ffff:/, '');

  if (process.env.NODE_ENV !== 'production' || allowedIPs.includes(cleanIP)) {
    return next();
  }

  return sendError(res, 403, 'FORBIDDEN', `Attendance only allowed from Workshop WiFi. Your IP: ${cleanIP}`);
};

// Mark Check-In
router.post('/check-in', requireAuth, requireRole('employee'), validateWorkshopIP, async (req, res) => {
  const today = new Date().toISOString().split('T')[0];
  
  let entry = await Attendance.findOne({
    where: {
      user_id: req.user.id,
      date: today
    }
  });

  if (entry && entry.check_in) {
    return sendError(res, 400, 'ALREADY_EXISTS', 'Already checked in for today');
  }

  if (!entry) {
    entry = await Attendance.create({
      user_id: req.user.id,
      date: today,
      check_in: new Date(),
      ip_address: req.ip.replace(/^::ffff:/, ''),
      status: 'present'
    });
  } else {
    entry.check_in = new Date();
    entry.ip_address = req.ip.replace(/^::ffff:/, '');
    await entry.save();
  }

  return res.json({ ok: true, attendance: entry });
});

// Mark Check-Out
router.post('/check-out', requireAuth, requireRole('employee'), validateWorkshopIP, async (req, res) => {
  const today = new Date().toISOString().split('T')[0];
  
  const entry = await Attendance.findOne({
    where: {
      user_id: req.user.id,
      date: today
    }
  });

  if (!entry || !entry.check_in) {
    return sendError(res, 400, 'NOT_FOUND', 'You must check-in first');
  }

  if (entry.check_out) {
    return sendError(res, 400, 'ALREADY_EXISTS', 'Already checked out for today');
  }

  entry.check_out = new Date();
  await entry.save();

  return res.json({ ok: true, attendance: entry });
});

// Get My Attendance (Employee)
router.get('/my', requireAuth, requireRole('employee'), async (req, res) => {
  const history = await Attendance.findAll({
    where: { user_id: req.user.id },
    order: [['date', 'DESC']],
    limit: 30
  });
  return res.json({ history });
});

// Get All Attendance (Admin)
router.get('/all', requireAuth, requireRole('admin', 'super_admin'), async (req, res) => {
  const { date } = req.query;
  const where = {};
  if (date) where.date = date;

  const history = await Attendance.findAll({
    where,
    include: [{ model: User, as: 'user', attributes: ['name', 'phone'] }],
    order: [['date', 'DESC'], ['check_in', 'DESC']]
  });
  return res.json({ history });
});

export default router;
