import { DataTypes, Model, Optional } from "sequelize";
import Joi from "joi";
import sequelize from "../middlewears/sequelize";

export interface IExpense {
  id: number;
  date: Date;
  expense: string;
  title?: string;
  price: string;
  isDeleted: boolean;
  createdAt?: Date;
  updatedAt?: Date;
}

interface IExpenseCreationAttributes
  extends Optional<
    IExpense,
    "id" | "title" | "isDeleted" | "createdAt" | "updatedAt"
  > {}

class ExpenseModel
  extends Model<IExpense, IExpenseCreationAttributes>
  implements IExpense
{
  public id!: number;
  public date!: Date;
  public expense!: string;
  public title?: string;
  public price!: string;
  public isDeleted!: boolean;

  public readonly createdAt!: Date;
  public readonly updatedAt!: Date;
}

ExpenseModel.init(
  {
    id: {
      type: DataTypes.INTEGER,
      autoIncrement: true,
      primaryKey: true,
    },
    date: {
      type: DataTypes.DATE,
      allowNull: false,
    },
    expense: {
      type: DataTypes.STRING,
      allowNull: false,
    },
    title: {
      type: DataTypes.STRING,
      allowNull: true,
    },
    price: {
      type: DataTypes.STRING,
      allowNull: false,
    },
    isDeleted: {
      type: DataTypes.BOOLEAN,
      defaultValue: false,
    },
    createdAt: {
      type: DataTypes.DATE,
      defaultValue: DataTypes.NOW,
    },
    updatedAt: {
      type: DataTypes.DATE,
      defaultValue: DataTypes.NOW,
    },
  },
  {
    tableName: "expenses",
    sequelize,
  }
);

const expenseSchema = Joi.object({
  date: Joi.date().required(),
  expense: Joi.string().required(),
  title: Joi.string().optional().allow(null, ""),
  price: Joi.string().required(),
});

export { ExpenseModel, expenseSchema };
