import { Model, DataTypes, Sequelize } from 'sequelize';
import { PAYMENT_TYPES, PAYMENT_STATUS } from '../../../common/config/constants.js';

export interface FinancePaymentAttributes {
    id: string;
    applicationId: string;
    paymentType: typeof PAYMENT_TYPES[keyof typeof PAYMENT_TYPES];
    amount: number;
    paymentStatus: typeof PAYMENT_STATUS[keyof typeof PAYMENT_STATUS];
    transactionId: string | null;
    paymentDate: Date | null;
    verifiedBy: string | null;
    verificationDate: Date | null;
    remarks: string | null;
}

export interface FinancePaymentInstance extends Model<FinancePaymentAttributes>, FinancePaymentAttributes { }

export default (sequelize: Sequelize) => {
    const FinancePayment = sequelize.define<FinancePaymentInstance>('FinancePayment', {
        id: {
            type: DataTypes.UUID,
            defaultValue: DataTypes.UUIDV4,
            primaryKey: true
        },
        applicationId: {
            type: DataTypes.UUID,
            allowNull: false,
            references: {
                model: 'applications',
                key: 'id'
            }
        },
        paymentType: {
            type: DataTypes.ENUM(...Object.values(PAYMENT_TYPES)),
            allowNull: false
        },
        amount: {
            type: DataTypes.DECIMAL(15, 2),
            allowNull: false
        },
        paymentStatus: {
            type: DataTypes.ENUM(...Object.values(PAYMENT_STATUS)),
            defaultValue: PAYMENT_STATUS.PENDING
        },
        transactionId: {
            type: DataTypes.STRING,
            allowNull: true
        },
        paymentDate: {
            type: DataTypes.DATE,
            allowNull: true
        },
        verifiedBy: {
            type: DataTypes.UUID,
            allowNull: true,
            references: {
                model: 'users',
                key: 'id'
            }
        },
        verificationDate: {
            type: DataTypes.DATE,
            allowNull: true
        },
        remarks: {
            type: DataTypes.TEXT,
            allowNull: true
        }
    }, {
        tableName: 'finance_payments',
        timestamps: true,
        indexes: [
            { fields: ['applicationId'] },
            { fields: ['paymentStatus'] }
        ]
    });

    (FinancePayment as any).associate = (models: any) => {
        FinancePayment.belongsTo(models.Application, {
            foreignKey: 'applicationId',
            as: 'application'
        });
        FinancePayment.belongsTo(models.User, {
            foreignKey: 'verifiedBy',
            as: 'verifier'
        });
    };

    return FinancePayment;
};
