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

// --- Payroll Run Model ---
const PayrollRun = sequelize.define('PayrollRun', {
    id: { type: DataTypes.UUID, defaultValue: DataTypes.UUIDV4, primaryKey: true },
    month: { type: DataTypes.STRING, allowNull: false }, // e.g., "2024-01"
    status: { type: DataTypes.ENUM('Draft', 'Processed', 'Paid'), defaultValue: 'Draft' },
    totalPaid: { type: DataTypes.DECIMAL(15, 2), defaultValue: 0 },
    processedBy: { type: DataTypes.UUID }
}, { timestamps: true });

// --- Payslip Model ---
const Payslip = sequelize.define('Payslip', {
    id: { type: DataTypes.UUID, defaultValue: DataTypes.UUIDV4, primaryKey: true },
    basic: { type: DataTypes.DECIMAL(15, 2), defaultValue: 0 },
    allowances: { type: DataTypes.DECIMAL(15, 2), defaultValue: 0 },
    deductions: { type: DataTypes.DECIMAL(15, 2), defaultValue: 0 },
    netPay: { type: DataTypes.DECIMAL(15, 2), defaultValue: 0 },
    status: { type: DataTypes.ENUM('Pending', 'Paid'), defaultValue: 'Pending' }
}, { timestamps: true });

// Relations
PayrollRun.hasMany(Payslip, { foreignKey: 'payrollRunId', onDelete: 'CASCADE' });
Payslip.belongsTo(PayrollRun, { foreignKey: 'payrollRunId' });

Staff.hasMany(Payslip, { foreignKey: 'staffId' });
Payslip.belongsTo(Staff, { foreignKey: 'staffId' });

PayrollRun.belongsTo(User, { foreignKey: 'processedBy', as: 'processor' });

module.exports = { PayrollRun, Payslip };
