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

export interface LoaRequestAttributes {
    id: string;
    applicationId: string | null;
    status: string;
    requestedBy: string | null;
    approvedAt: Date | null;
    approvedBy: string | null;
}

export interface LoaRequestInstance extends Model<LoaRequestAttributes>, LoaRequestAttributes { }

export default (sequelize: Sequelize) => {
    const LoaRequest = sequelize.define<LoaRequestInstance>('LoaRequest', {
        id: {
            type: DataTypes.UUID,
            defaultValue: DataTypes.UUIDV4,
            primaryKey: true
        },
        applicationId: {
            type: DataTypes.UUID,
            allowNull: true,
            references: {
                model: 'applications',
                key: 'id'
            }
        },
        status: {
            type: DataTypes.STRING,
            defaultValue: 'pending'
        },
        requestedBy: {
            type: DataTypes.UUID,
            allowNull: true,
            references: {
                model: 'users',
                key: 'id'
            }
        },
        approvedAt: {
            type: DataTypes.DATE,
            allowNull: true
        },
        approvedBy: {
            type: DataTypes.UUID,
            allowNull: true,
            references: {
                model: 'users',
                key: 'id'
            }
        }
    }, {
        tableName: 'loa_requests',
        timestamps: true
    });

    (LoaRequest as any).associate = (models: any) => {
        LoaRequest.belongsTo(models.Application, { foreignKey: 'applicationId', as: 'application' });
        LoaRequest.belongsTo(models.User, { foreignKey: 'requestedBy', as: 'requester' });
        LoaRequest.belongsTo(models.User, { foreignKey: 'approvedBy', as: 'approver' });

        LoaRequest.hasMany(models.LoaApproval, { foreignKey: 'requestId', as: 'approvals' });
        LoaRequest.hasMany(models.LoaDocumentGenerated, { foreignKey: 'requestId', as: 'generatedDocuments' });
    };

    return LoaRequest;
};
