import { Request, Response } from "express";
import { ExpenseModel, expenseSchema } from "../models/expense";

const createExpense = async (req: Request, res: Response) => {
  const { error } = expenseSchema.validate(req.body);
  if (error) return res.status(400).json({ error: error.details[0].message });

  try {
    const expense = new ExpenseModel(req.body);
    await expense.save();
    res
      .status(200)
      .json({ message: "Expense created successfully", id: expense.id });
  } catch (ex) {
    res.status(500).json({ error: "An unexpected error occurred." });
  }
};

const getAllExpenses = async (req: Request, res: Response) => {
  try {
    const expenses = await ExpenseModel.findAll({
      where: { isDeleted: false },
    });
    res.status(200).json(expenses);
  } catch (ex) {
    res.status(500).json({ error: "An unexpected error occurred." });
  }
};

const getExpenseById = async (req: Request, res: Response) => {
  try {
    const expense = await ExpenseModel.findOne({
      where: { id: req.params.id, isDeleted: false },
    });
    if (!expense) return res.status(404).json({ error: "Expense not found." });
    res.status(200).json(expense);
  } catch (ex) {
    res.status(500).json({ error: "An unexpected error occurred." });
  }
};

const updateExpense = async (req: Request, res: Response) => {
  try {
    const expense = await ExpenseModel.findOne({
      where: { id: req.params.id, isDeleted: false },
    });
    if (!expense) return res.status(404).json({ error: "Expense not found." });

    await expense.update(req.body);
    res.status(200).json({ message: "Expense updated successfully" });
  } catch (ex) {
    res.status(500).json({ error: "An unexpected error occurred." });
  }
};

const deleteExpense = async (req: Request, res: Response) => {
  try {
    const expense = await ExpenseModel.findOne({
      where: { id: req.params.id, isDeleted: false },
    });
    if (!expense) return res.status(404).json({ error: "Expense not found." });

    await expense.update({ isDeleted: true });
    res.status(200).json({ message: "Expense deleted successfully" });
  } catch (ex) {
    res.status(500).json({ error: "An unexpected error occurred." });
  }
};

export {
  createExpense,
  getAllExpenses,
  getExpenseById,
  updateExpense,
  deleteExpense,
};
