const { DataTypes } = require('sequelize');
const { sequelize } = require('../config/db');
const { Invoice } = require('./billing');
const { Client } = require('./client');

const Payment = sequelize.define('Payment', {
    id: { type: DataTypes.UUID, defaultValue: DataTypes.UUIDV4, primaryKey: true },
    amount: { type: DataTypes.DECIMAL(15, 2), allowNull: false },
    paymentDate: { type: DataTypes.DATE, defaultValue: DataTypes.NOW },
    paymentMethod: {
        type: DataTypes.ENUM('MPesa', 'Bank', 'Cash', 'Credit Card', 'Other'),
        defaultValue: 'MPesa'
    },
    transactionReference: { type: DataTypes.STRING },
    bankAccountId: { type: DataTypes.UUID },
    status: {
        type: DataTypes.ENUM('Pending', 'Completed', 'Failed'),
        defaultValue: 'Completed'
    }
}, {
    tableName: 'Payments',
    timestamps: true
});

const { BankAccount } = require('./banking');
Payment.belongsTo(BankAccount, { foreignKey: 'bankAccountId' });
BankAccount.hasMany(Payment, { foreignKey: 'bankAccountId' });

// Relations
Invoice.hasMany(Payment, { foreignKey: 'invoiceId' });
Payment.belongsTo(Invoice, { foreignKey: 'invoiceId' });

Client.hasMany(Payment, { foreignKey: 'clientId' });
Payment.belongsTo(Client, { foreignKey: 'clientId' });

module.exports = { Payment };
