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

export interface RolePermissionAttributes {
    id: string;
    roleId: string;
    permissionId: string;
}

export interface RolePermissionInstance extends Model<RolePermissionAttributes>, RolePermissionAttributes { }

export default (sequelize: Sequelize) => {
    const RolePermission = sequelize.define<RolePermissionInstance>('RolePermission', {
        id: {
            type: DataTypes.UUID,
            defaultValue: DataTypes.UUIDV4,
            primaryKey: true
        },
        roleId: {
            type: DataTypes.UUID,
            allowNull: false,
            references: {
                model: 'roles',
                key: 'id'
            }
        },
        permissionId: {
            type: DataTypes.UUID,
            allowNull: false,
            references: {
                model: 'permissions',
                key: 'id'
            }
        }
    }, {
        tableName: 'role_permissions',
        timestamps: true,
        updatedAt: false
    });

    (RolePermission as any).associate = (models: any) => {
        RolePermission.belongsTo(models.Role, {
            foreignKey: 'roleId',
            as: 'role'
        });
        RolePermission.belongsTo(models.Permission, {
            foreignKey: 'permissionId',
            as: 'permission'
        });
    };

    return RolePermission;
};
