import mongoose from 'mongoose';

import Transaction from '../models/transaction.js';
import catchAsync from '../utils/catchAsync.js';

export const getTransactions = catchAsync(async (req, res) => {
  const transactions = await Transaction.find({});

  res.status(200).json(transactions);
});

export const createTransaction = catchAsync(async (req, res) => {
  const transaction = req.body;

  const newTransaction = new Transaction(transaction);
  await newTransaction.save();

  res.status(201).json(newTransaction);
});

export const updateTransaction = catchAsync(async (req, res) => {
  const { id: _id } = req.params;
  const transaction = req.body;

  if (!mongoose.Types.ObjectId.isValid(_id)) {
    return res.status(404).json({ message: 'No transaction with that id!' });
  }

  const updateTransaction = await Transaction.findByIdAndUpdate(
    _id,
    transaction,
    { new: true }
  );

  res.json(updateTransaction);
});

export const deleteTransaction = catchAsync(async (req, res) => {
  const { id } = req.params;

  if (!mongoose.Types.ObjectId.isValid(id)) {
    return res.status(404).json({ message: 'No transaction with that id' });
  }

  await Transaction.findByIdAndDelete(id);

  res.json({ message: 'Transaction deleted successfully!' });
});
