import { Model, DataTypes, Sequelize } from 'sequelize';

export interface SecurityDepositAttributes {
    id: string;
    applicationId: string | null;
    amount: number;
    paymentReference: string | null;
    proofDocumentId: string | null;
    status: string;
    depositType: 'SECURITY_DEPOSIT' | 'FIRST_FILL';
    verifiedAt: Date | null;
    verifiedBy: string | null;
}

export interface SecurityDepositInstance extends Model<SecurityDepositAttributes>, SecurityDepositAttributes { }

export default (sequelize: Sequelize) => {
    const SecurityDeposit = sequelize.define<SecurityDepositInstance>('SecurityDeposit', {
        id: {
            type: DataTypes.UUID,
            defaultValue: DataTypes.UUIDV4,
            primaryKey: true
        },
        applicationId: {
            type: DataTypes.UUID,
            allowNull: true,
            references: {
                model: 'applications',
                key: 'id'
            }
        },
        amount: {
            type: DataTypes.DECIMAL(15, 2),
            allowNull: false
        },
        paymentReference: {
            type: DataTypes.STRING,
            allowNull: true
        },
        proofDocumentId: {
            type: DataTypes.UUID,
            allowNull: true,
            references: {
                model: 'onboarding_documents',
                key: 'id'
            }
        },
        status: {
            type: DataTypes.STRING,
            defaultValue: 'pending'
        },
        depositType: {
            type: DataTypes.ENUM('SECURITY_DEPOSIT', 'FIRST_FILL'),
            allowNull: false,
            defaultValue: 'SECURITY_DEPOSIT'
        },
        verifiedAt: {
            type: DataTypes.DATE,
            allowNull: true
        },
        verifiedBy: {
            type: DataTypes.UUID,
            allowNull: true,
            references: {
                model: 'users',
                key: 'id'
            }
        }
    }, {
        tableName: 'security_deposits',
        timestamps: true
    });

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

    return SecurityDeposit;
};
