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

// --- Expense Category Model ---
const ExpenseCategory = sequelize.define('ExpenseCategory', {
    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: 'ExpenseCategories',
    timestamps: true
});

// --- Vendor Model ---
const Vendor = sequelize.define('Vendor', {
    id: { type: DataTypes.UUID, defaultValue: DataTypes.UUIDV4, primaryKey: true },
    name: { type: DataTypes.STRING, allowNull: false },
    contactPerson: { type: DataTypes.STRING },
    email: { type: DataTypes.STRING },
    phone: { type: DataTypes.STRING },
    notes: { type: DataTypes.TEXT },
    creditBalance: { type: DataTypes.DECIMAL(15, 2), defaultValue: 0.00 }
}, {
    tableName: 'Vendors',
    timestamps: true
});

// --- Expense Model ---
const Expense = sequelize.define('Expense', {
    id: { type: DataTypes.UUID, defaultValue: DataTypes.UUIDV4, primaryKey: true },
    amount: { type: DataTypes.DECIMAL(15, 2), allowNull: false },
    paymentMethod: { type: DataTypes.STRING },
    reference: { type: DataTypes.STRING },
    expenseDate: { type: DataTypes.DATEONLY, allowNull: false },
    receiptPath: { type: DataTypes.STRING }, // TODO: Implement file upload in Phase 3
    notes: { type: DataTypes.TEXT },
    createdBy: { type: DataTypes.UUID },
    status: { type: DataTypes.STRING, defaultValue: 'PAID' }, // PAID, PENDING, PARTIAL
    balanceDue: { type: DataTypes.DECIMAL(15, 2), defaultValue: 0.00 }
}, {
    tableName: 'Expenses',
    timestamps: true,
    indexes: [
        { fields: ['expenseDate'] },
        { fields: ['expenseCategoryId'] },
        { fields: ['vendorId'] },
        { fields: ['status'] }
    ]
});

// Relations
ExpenseCategory.hasMany(Expense, { foreignKey: 'expenseCategoryId' });
Expense.belongsTo(ExpenseCategory, { foreignKey: 'expenseCategoryId' });

Vendor.hasMany(Expense, { foreignKey: 'vendorId' });
Expense.belongsTo(Vendor, { foreignKey: 'vendorId' });

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

module.exports = { ExpenseCategory, Vendor, Expense };
