import {
  UserManagementModel,
  userManagementValidationSchema,
} from "../models/user_management";
import { Request, Response } from "express";

/// Create new user management
export const createUserManagement = async (req: Request, res: Response) => {
  const { error } = userManagementValidationSchema.validate(req.body);
  if (error) return res.status(400).json({ error: error.details[0].message });

  try {
    const newUserManagement = await UserManagementModel.create(req.body);
    return res
      .status(200)
      .json({
        message: "User created successfully.",
        id: newUserManagement.id,
      });
  } catch (ex) {
    return res.status(500).json({ error: "An unexpected error occurred." });
  }
};

/// Get all user managements
export const getAllUserManagements = async (req: Request, res: Response) => {
  try {
    const userManagements = await UserManagementModel.findAll({
      where: { isDeleted: false },
    });
    return res.status(200).json(userManagements);
  } catch (ex) {
    return res.status(500).json({ error: "An unexpected error occurred." });
  }
};

/// Update existing user management
export const updateUserManagement = async (req: Request, res: Response) => {
  try {
    // Find the user management by ID
    const userManagement = await UserManagementModel.findByPk(req.params.id);
    if (!userManagement)
      return res.status(404).json({ error: "User not found." });

    // Validate the request body
    const { error } = userManagementValidationSchema.validate(req.body);
    if (error) return res.status(400).json({ error: error.details[0].message });

    // Update the user management details
    await userManagement.update(req.body);

    // Send success response
    return res
      .status(200)
      .json({ message: "User updated successfully.", id: userManagement.id });
  } catch (ex) {
    console.error(`Error updating user: ${ex}`);
    return res.status(500).json({ error: "An unexpected error occurred." });
  }
};

/// Delete a user management
export const deleteUserManagement = async (req: Request, res: Response) => {
  try {
    // Find the user management by ID
    const userManagement = await UserManagementModel.findByPk(req.params.id);
    if (!userManagement)
      return res.status(404).json({ error: "User not found." });

    // Soft delete the user management
    await userManagement.update({ isDeleted: true });

    // Send success response
    return res.status(200).json({ message: "User deleted successfully." });
  } catch (ex) {
    return res.status(500).json({ error: "An unexpected error occurred." });
  }
};
