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

const router = Router();

router.patch('/me', requireAuth, async (req, res) => {
  const name = req.body?.name;
  if (typeof name !== 'string' || !name.trim()) {
    return sendError(res, 400, 'VALIDATION_ERROR', 'name is required');
  }
  await User.update({ name: name.trim() }, { where: { id: req.user.id } });
  const user = await User.findByPk(req.user.id, {
    attributes: ['id', 'name', 'phone', 'role'],
    raw: true,
  });
  return res.json({ user });
});

router.get('/employees', requireAuth, requireRole('admin', 'super_admin'), async (_req, res) => {
  const rows = await User.findAll({
    where: { role: 'employee' },
    attributes: ['id', 'name', 'phone', 'role'],
    order: [['name', 'ASC']],
    raw: true,
  });
  return res.json({ users: rows });
});

router.post('/employees', requireAuth, requireRole('super_admin'), async (req, res) => {
  const { name, phone } = req.body;
  
  if (!name || !phone) {
    return sendError(res, 400, 'VALIDATION_ERROR', 'Name and phone are required');
  }
  
  if (!/^\d{10,15}$/.test(phone)) {
    return sendError(res, 400, 'VALIDATION_ERROR', 'Invalid phone number format');
  }

  const existing = await User.findOne({ where: { phone } });
  if (existing) {
    return sendError(res, 400, 'VALIDATION_ERROR', 'Phone number already registered');
  }

  const user = await User.create({
    name: name.trim(),
    phone: phone.trim(),
    role: 'employee',
  });

  return res.status(201).json({
    user: {
      id: Number(user.id),
      name: user.name,
      phone: user.phone,
      role: user.role,
    },
  });
});

export default router;
