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

// --- Income Category Model ---
const IncomeCategory = sequelize.define('IncomeCategory', {
    id: { type: DataTypes.INTEGER, autoIncrement: true, primaryKey: true },
    name: { type: DataTypes.STRING, allowNull: false, unique: true },
    description: { type: DataTypes.TEXT },
    isActive: { type: DataTypes.BOOLEAN, defaultValue: true }
}, {
    tableName: 'IncomeCategories',
    timestamps: true
});

// --- Income Model ---
const Income = sequelize.define('Income', {
    id: { type: DataTypes.UUID, defaultValue: DataTypes.UUIDV4, primaryKey: true },
    amount: { type: DataTypes.DECIMAL(15, 2), allowNull: false },
    source: {
        type: DataTypes.ENUM('MANUAL', 'CRM'),
        defaultValue: 'MANUAL'
    },
    reference: { type: DataTypes.STRING },
    paymentMethod: { type: DataTypes.STRING, defaultValue: 'Cash' },
    receivedDate: { type: DataTypes.DATEONLY, allowNull: false },
    notes: { type: DataTypes.TEXT },
    isReadOnly: { type: DataTypes.BOOLEAN, defaultValue: false },
    crmSource: { type: DataTypes.BOOLEAN, defaultValue: false },
    createdBy: { type: DataTypes.UUID }
}, {
    tableName: 'Incomes',
    timestamps: true,
    indexes: [
        { fields: ['receivedDate'] },
        { fields: ['incomeCategoryId'] }
    ]
});

// Relations
IncomeCategory.hasMany(Income, { foreignKey: 'incomeCategoryId' });
Income.belongsTo(IncomeCategory, { foreignKey: 'incomeCategoryId' });

Income.belongsTo(User, { foreignKey: 'createdBy', as: 'creator' });

module.exports = { IncomeCategory, Income };
