const { DataTypes } = require('sequelize');
const { sequelize } = require('../config/db');

const BankAccount = sequelize.define('BankAccount', {
    id: { type: DataTypes.UUID, defaultValue: DataTypes.UUIDV4, primaryKey: true },
    bankName: { type: DataTypes.STRING, allowNull: false },
    accountName: { type: DataTypes.STRING },
    accountNumber: { type: DataTypes.STRING, allowNull: false, unique: true },
    openingBalance: { type: DataTypes.DECIMAL(15, 2), defaultValue: 0 },
    currentBalance: { type: DataTypes.DECIMAL(15, 2), defaultValue: 0 },
    isDefault: { type: DataTypes.BOOLEAN, defaultValue: false },
    isActive: { type: DataTypes.BOOLEAN, defaultValue: true }
}, {
    tableName: 'BankAccounts',
    timestamps: true
});

const BankTransaction = sequelize.define('BankTransaction', {
    id: { type: DataTypes.UUID, defaultValue: DataTypes.UUIDV4, primaryKey: true },
    type: { type: DataTypes.ENUM('Credit', 'Debit'), allowNull: false },
    amount: { type: DataTypes.DECIMAL(15, 2), allowNull: false },
    description: { type: DataTypes.STRING },
    reference: { type: DataTypes.STRING }, // e.g. Invoice #, Receipt #
    module: { type: DataTypes.STRING }, // e.g. 'Income', 'Expense', 'Manual'
    referenceId: { type: DataTypes.STRING }, // ID of the source document
    balanceAfter: { type: DataTypes.DECIMAL(15, 2) },
    transactionDate: { type: DataTypes.DATE, defaultValue: DataTypes.NOW }
}, {
    tableName: 'BankTransactions',
    timestamps: true
});

// Relations
BankAccount.hasMany(BankTransaction, { foreignKey: 'bankAccountId', as: 'transactions' });
BankTransaction.belongsTo(BankAccount, { foreignKey: 'bankAccountId' });

module.exports = { BankAccount, BankTransaction };
