const { DataTypes } = require('sequelize');
const db = require('../config/database');
const Users = require('./UserModel');
const Accounts = require('./AccountModel');
const Categories = require('./CategoryModel');

const Transactions = db.define('transactions', {
    id: {
        type: DataTypes.INTEGER,
        primaryKey: true,
        autoIncrement: true
    },
    amount: {
        type: DataTypes.DECIMAL(15,2),
        allowNull: false
    },
    description: {
        type: DataTypes.STRING,
        allowNull: false
    },
    date: {
        type: DataTypes.DATEONLY,
        defaultValue: DataTypes.NOW
    },
    type: {
        type: DataTypes.ENUM('INCOME', 'EXPENSE'),
        allowNull: false
    },
    user_id: {
        type: DataTypes.INTEGER,
        references: { model: Users, key: 'id'}
    },
    account_id: {
        type: DataTypes.INTEGER,
        references: {model: Accounts, key: 'id'}
    },
    category_id: {
        type: DataTypes.INTEGER,
        references: {model: Categories, key: 'id'}
    }
},{
    freezeTableName: true
});

Users.hasMany(Transactions, { foreignKey: 'user_id' });
Accounts.hasMany(Transactions, { foreignKey: 'account_id' });
Categories.hasMany(Transactions, { foreignKey: 'category_id' });
Transactions.belongsTo(Accounts, { foreignKey: 'account_id'});
Transactions.belongsTo(Categories, { foreignKey: 'category_id'});

module.exports = Transactions;