const prisma = require('../models/prisma');
const bcrypt = require('bcryptjs');
const { validationResult } = require('express-validator');

exports.getAll = async (req, res, next) => {
  try {
    const users = await prisma.user.findMany({
      where: { isActive: true },
      select: { id: true, email: true, firstName: true, lastName: true, role: true, department: true, jobTitle: true, avatarUrl: true, lastLoginAt: true },
      orderBy: { firstName: 'asc' },
    });
    res.json({ users });
  } catch (err) { next(err); }
};

exports.getById = async (req, res, next) => {
  try {
    const user = await prisma.user.findUniqueOrThrow({
      where: { id: req.params.id },
      select: { id: true, email: true, firstName: true, lastName: true, role: true, department: true, jobTitle: true, phone: true, avatarUrl: true, isActive: true, lastLoginAt: true, createdAt: true },
    });
    res.json({ user });
  } catch (err) { next(err); }
};

exports.create = async (req, res, next) => {
  try {
    const errors = validationResult(req);
    if (!errors.isEmpty()) return res.status(400).json({ errors: errors.array() });
    const { password, ...rest } = req.body;
    const passwordHash = await bcrypt.hash(password, 12);
    const user = await prisma.user.create({
      data: { ...rest, passwordHash },
      select: { id: true, email: true, firstName: true, lastName: true, role: true },
    });
    res.status(201).json({ user });
  } catch (err) { next(err); }
};

exports.update = async (req, res, next) => {
  try {
    const { password, ...rest } = req.body;
    const data = { ...rest };
    if (password) data.passwordHash = await bcrypt.hash(password, 12);
    const user = await prisma.user.update({
      where: { id: req.params.id },
      data,
      select: { id: true, email: true, firstName: true, lastName: true, role: true, department: true, jobTitle: true },
    });
    res.json({ user });
  } catch (err) { next(err); }
};
